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.
In PHP 7, type hinting can be used to specify the expected data type of a function or method parameter. However, PHP 7 does not support specifying element types within an array natively; only the bare array keyword is valid. To indicate that an array should contain specific object types, developers typically use PHPDoc comments combined with manual runtime validation.
Example of type hinting in PHP 7
<?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" (PHP 7 only enforces that it is an array)
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
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Learn object oriented PHP</div>
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.
Example of specifying the class name of the objects in PHP 7
<?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) {
// PHPDoc indicates expected element type, but runtime validation is required since PHP 7 type hints do not enforce array element types.
if (!$person instanceof Person) {
// Handle the error or skip
continue;
}
echo "Name: " . $person->name . ", Age: " . $person->age . "\n";
}
}
someFunction($arrayOfPeople);This approach ensures that only arrays containing objects of the specified class are processed, compensating for the lack of native element-type enforcement in PHP 7.