PHPでオブジェクトの配列をforeach文で繰り返し処理する方法は何ですか?

PHPでは、オブジェクト配列をループ処理するためにforeach文を使用することができます。以下は一つの例です:

class Person {
    public $name;
    public $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

// 创建一个对象数组
$people = [
    new Person('John', 20),
    new Person('Jane', 25),
    new Person('Mike', 30)
];

// 使用 foreach 遍历对象数组
foreach ($people as $person) {
    echo $person->name . ' is ' . $person->age . ' years old.' . PHP_EOL;
}

結果は出力されます。

John is 20 years old.
Jane is 25 years old.
Mike is 30 years old.
bannerAds