也许我遗漏了一些东西,但是否有任何选项来定义该函数应该有参数或返回例如用户对象数组?
考虑以下代码:
<?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 中。如果不包含,你有任何线索为什么它是添加类型提示时不包括在内?
最佳答案
不包括在内。
If it's not included, do you have Any clue why it was not included when type hinting was added?
使用当前的数组实现,需要在运行时检查所有数组元素,因为数组本身不包含类型信息。
实际上已经为 PHP 5.6 提出过但被拒绝了:RFC "arrayof" - 有趣的是,并不是因为性能问题被证明可以忽略不计,而是因为对于应该如何实现它没有达成一致意见。也有人反对,如果没有标量类型提示,它是不完整的。如果您对整个讨论感兴趣,请阅读 in the mailing list archive .
恕我直言,数组类型提示将与类型化数组一起提供最大的好处,我很乐意看到它们实现。
所以也许是时候制定一个新的 RFC 并重新开始讨论了。
部分解决方法:
您可以键入提示可变参数,从而将签名写为
function findUserByAge(int $age, User ...$users) : array
用法:
findUserByAge(15, ...$userInput);
在此调用中,参数 $userInput
将被“解包”为单个变量,并在方法本身中“打包”回数组 $users
。每个项目都被验证为 User
类型。 $userInput
也可以是一个迭代器,它会被转换成一个数组。
很遗憾,对于返回类型没有类似的解决方法,您只能将其用于最后一个参数。
关于php - PHP 7 中的类型提示 - 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34273367/