php中怎么用foreach遍历对象数组

avatar
作者
筋斗云
阅读量:0

在 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. 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!