php数组里可以放对象吗

PhpPhp 2023-08-28 21:24:44 800
摘要: 在PHP中,是可以在数组中存储对象的。以下是一个使用PHP数组存放对象的示例:classPerson{publicstring$name;publicint$age;publicfunction__construct(string$name,int$age){$th...

在PHP中,是可以在数组中存储对象的。

以下是一个使用 PHP 数组存放对象的示例:

class Person {
    public string $name;
    public int $age;
    public function __construct(string $name, int $age) {
        $this->name = $name;
        $this->age = $age;
    }
}
// 创建三个 Person 对象
$person1 = new Person("Alice", 25);
$person2 = new Person("Bob", 30);
$person3 = new Person("Charlie", 35);
// 将这三个对象存放进数组中
$people = array($person1, $person2, $person3);
// 遍历这个数组并输出每个对象的属性
foreach ($people as $person) {
    echo "Name: " . $person->name . "; Age: " . $person->age . "\n";
}