溫馨提示×

php中怎么用foreach遍歷對象數組

PHP
小億
114
2023-12-27 17:04:18
欄目: 編程語言

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

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女