也许我遗漏了一些东西,但是有没有任何选项来定义函数应该有参数或返回例如用户对象的数组?
考虑以下代码:
<?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
应该返回用户数组?我希望当类型提示被添加的时候,它应该是可能的,但是我没有找到任何关于对象数组的类型提示的信息,所以它可能不包含在 PHP 7中。如果没有包含它,那么您知道添加类型提示时为什么没有包含它吗?