Source Code:
(back to article)
<?php class Person { public $name; public $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } } // Define an array of Person objects $arrayOfPeople = [ new Person("John", 30), new Person("Jane", 25) ]; /** * Demonstrates type hinting for an array of Person objects using PHPDoc. * * @param Person[] $arrayOfPeople An array of Person objects */ function someFunction(array $arrayOfPeople) { foreach ($arrayOfPeople as $person) { // Ensures that $person is indeed an instance of Person if (!$person instanceof Person) { // Handle the error or skip continue; } echo "Name: " . $person->name . ", Age: " . $person->age . "\n"; } } someFunction($arrayOfPeople);
Result:
Report an issue