参数不受限制的类方法

时间:2017-11-06 23:29:10

标签: php arrays

我有以下代码:

$array = array('foo', 'foo', 'bar', 'bis', 'ter')
Arrays::without($array, 'foo', 'bis') // Returns array('bar', 'ter')

如您所见,调用Arrays::without函数的第二个和第三个参数。您可以根据需要传递任意数量的参数,例如:

Arrays::without($array, 'foo', 'bis','athirdparam','afourthparam') // Returns array('bar', 'ter')

我试图将它封装到我有的类中的静态方法中:

public static function without($arr,$p)
{
    return Arrays::without($arr,$p);
}

我需要知道的是,如果有一种方法可以将无限制的参数传递给此方法without并在我的函数调用中使用它们Arrays::without

2 个答案:

答案 0 :(得分:2)

您可以致电:

Arrays::without($arr, ...$p);

$p是一个数组,或者像这样编写你的方法:

public static function without($arr,$p)
{
    return Arrays::without($arr, ...$p);
}

但这是非常不必要的。

检查splat运算符:http://php.net/manual/en/migration56.new-features.php#migration56.new-features.splat

答案 1 :(得分:0)

在函数内部使用func_get_args(),或在函数签名中使用public static function without(...$args) ....这些都是here in the PHP Docs