Возможно, я что-то пропустил, но есть ли возможность определить, что функция должна иметь аргумент или возвращать массив массива объектов User?
Рассмотрим следующий код:
<?php
class User
{
protected $name;
protected $age;
/**
* User constructor.
*
* @param $name
*/
public function __construct(string $name, int $age)
{
$this->name = $name;
$this->age = $age;
}
/**
* @return mixed
*/
public function getName() : string
{
return $this->name;
}
public function getAge() : int
{
return $this->age;
}
}
function findUserByAge(int $age, array $users) : array
{
$result = [];
foreach ($users as $user) {
if ($user->getAge() == $age) {
if ($user->getName() == 'John') {
// complicated code here
$result[] = $user->getName(); // bug
} else {
$result[] = $user;
}
}
}
return $result;
}
$users = [
new User('John', 15),
new User('Daniel', 25),
new User('Michael', 15),
];
$matches = findUserByAge(15, $users);
foreach ($matches as $user) {
echo $user->getName() . ' '.$user->getAge() . "\n";
}
Есть ли какой-либо параметр в PHP7, чтобы сказать, что функция findUserByAge
должна возвращать массив пользователей? Я ожидал бы, что при добавлении типа hinting это должно быть возможно, но я не нашел никакой информации для типа hinting для массива объектов, поэтому, вероятно, он не был включен в PHP 7. Если он не включен, есть ли у вас какие-либо подсказки, почему это было не включается, когда был добавлен тип hinting?