Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 类型提示模型数组_Php_Arrays_Laravel_Type Hinting - Fatal编程技术网

Php 类型提示模型数组

Php 类型提示模型数组,php,arrays,laravel,type-hinting,Php,Arrays,Laravel,Type Hinting,我想知道您是否可以在php中键入一个模型数组(更明确地说是Laravel) 代码示例: use App\User; public function index(User $user) { // do something with the user } 我的问题是,有没有一种方法可以键入一系列用户模型: use App\User; public function index(array User $users) //this is wrong .. { // do somet

我想知道您是否可以在php中键入一个模型数组(更明确地说是Laravel)

代码示例:

use App\User;

public function index(User $user)
{
    // do something with the user
}
我的问题是,有没有一种方法可以键入一系列用户模型:

use App\User;

public function index(array User $users) //this is wrong ..
{
    // do something with the users
}

不,你不能这样做。您所能做的最好是将参数作为数组键入hint。您可以在此处阅读有关PHP中类型暗示的更多信息:

更新
在PHP5.6+中,您可以使用可变长度参数列表来实现所需的功能。检查

我知道答案已经被接受,但这是可能的一半,这取决于您的IDE实现phpDoc的程度(PhpStorm确实支持这一点,但我们去年在让Eclipse支持它方面遇到了问题)

phpDoc通过
Class[]
语法支持类型化数组。所以你可以做:

use App\User;

/**
 * @var User[] $user
 */
public function index(array $users)
{
    // do something with the users
}
这不会限制某人将非
用户
对象数组传递到
索引
(就像在字符串中传递
数组
类型一样),但它将为他们提供预期的指导,并允许您在执行以下操作时获得代码提示:

foreach ($users as $user) {
    $user->dele // Depending on IDE, this will code hint/complete "delete()"
}

在PHP5.6+中,您可以使用它来实现您想要的功能

在调用函数时解包变量,函数在其签名中使用变量参数。因此,不要传递一个
User
对象数组,而是将
User
对象的
数组
集合
解包,并根据您提供的类型提示检查所有这些对象

示例:

function deleteUsers(User ...$users)
{
    // delete the users here
}

$users = [$user1, $user2, $user3];

deleteUsers(...$users);
解包将在常规
数组
和Laravel
集合
对象或任何其他
可遍历的
变量或文字上工作,以输入参数列表

这相当于执行以下操作:

deleteUsers($user1, $user2, $user3);

由于它是Laravel,如果您希望从一个雄辩的查询中得到结果,那么您可以键入hint Eloquent\Collection,但显然您不知道它是一个用户集合!也许可以扩展到
elountent\Collection
App\UserCollection
?好主意,你能拓宽你的思路吗?不明白为什么这不是公认的答案,或者为什么它有0票:eye\u roll\u emoji:谢谢罗伯特。你必须问@rvandersteen:)