PHP-Laravel集合或数组的类型提示 [英] PHP - Type hint for Laravel Collection or Array

查看:147
本文介绍了PHP-Laravel集合或数组的类型提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个函数,该函数接受任何可遍历对象作为参数,例如Laravel Collection/Array.有什么方法可以在函数参数中键入提示此条件的提示吗?

I would like to create a function which accepts any traversable object as parameter, for example Laravel Collection/Array. Is there any way to type hint this condition in the function parameter??

我希望在单一定义中同时满足以下两项要求:

I want the effect of both the following in single definition:

function test(array $traversable)
{
    print_r($traversable);
}

AND

function test(Illuminate\Support\Collection $traversable)
{
    print_r($traversable);
}

并且DocBlock应该是

AND the DocBlock should be

/**
 * Function to do something
 * 
 * @param Collection|Array $traversable Traversable parameter
 * @return null Absolutely nothing
 */

推荐答案

PHP 7.1将引入iterable typehint,它将完全做到这一点:

PHP 7.1 will introduce the iterable typehint which will do exactly that:

function test(iterable $items) { /*...*/ }

请参见 PHP-rfc:iterable .

在此之前,如果要同时接受Traversablearray,则不能使用任何typehint.您唯一可以做的就是使用适当的@param注释对其进行记录:

Until then you can't use any typehint if you want to accept both Traversable and array. The only thing you can do is use a proper @param annotation to document it:

/**
 * @param \Traversable|array $items
 */
function test($items) { /*...*/ }

这篇关于PHP-Laravel集合或数组的类型提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆