Type hinting in PHP 7 - array of objects
In PHP 7, type hinting can be used to specify the expected data type of a function or method parameter. To specify an array of objects, the parameter type hint would be "array" and the class name of the objects within the array, like this:
<?php
// Define an array of objects
$arrayOfObjects = [(object) ["name" => "John", "age" => 30], (object) ["name" => "Jane", "age" => 25]];
// Define a function with a type hint for the parameter "arrayOfObjects"
function someFunction(array $arrayOfObjects)
{
// Iterate over the array of objects
foreach ($arrayOfObjects as $object) {
// Output the name and age of each object
echo "Name: " . $object->name . ", Age: " . $object->age . "\n";
}
}
// Call the function with the defined array of objects
someFunction($arrayOfObjects);
// Output:
// Name: John, Age: 30
// Name: Jane, Age: 25
In PHP, specifying an array of specific object types using PHPDoc comments enhances code documentation and IDE support, indicating expected parameter types for better development experience. However, PHP runtime doesn't enforce these hints, necessitating manual type checks within functions to ensure each element matches the expected object type. This approach marries the clarity of type expectations with the necessity of runtime validation for robust, error-resistant code.
<?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);
This will ensure that only arrays containing objects of the specified class can be passed as an argument to the function.