在PHP函数签名中模拟Ruby"splat"运算符的最佳方法[方法重载]

mač*_*ček 5 php ruby overloading

在Ruby中

def my_func(foo,bar,*zim)
  [foo, bar, zim].collect(&:inspect)
end

puts my_func(1,2,3,4,5)

# 1
# 2
# [3, 4, 5]
Run Code Online (Sandbox Code Playgroud)

在PHP(5.3)

function my_func($foo, $bar, ... ){
  #...
}
Run Code Online (Sandbox Code Playgroud)

在PHP中执行此操作的最佳方法是什么?

JCM*_*JCM 10

从与此相关的其他问题复制我的答案:

现在可以使用PHP 5.6.x,使用...运算符(在某些语言中也称为splat运算符):

例:

function addDateIntervalsToDateTime( DateTime $dt, DateInterval ...$intervals )
{
    foreach ( $intervals as $interval ) {
        $dt->add( $interval );
    }
    return $dt;
}
Run Code Online (Sandbox Code Playgroud)


Gor*_*don 7

尝试

Ruby Snippet的PHP版本

function my_func($foo, $bar)
{
    $arguments = func_get_args();
    return array(
        array_shift($arguments),
        array_shift($arguments),
        $arguments
    );
}
print_r( my_func(1,2,3,4,5,6) );
Run Code Online (Sandbox Code Playgroud)

要不就

function my_func($foo, $bar)
{
    return array($foo , $bar , array_slice(func_get_args(), 2));
}
Run Code Online (Sandbox Code Playgroud)

Array
(
    [0] => 1
    [1] => 2
    [2] => Array
        (
            [0] => 3
            [1] => 4
            [2] => 5
            [3] => 6
        )
)
Run Code Online (Sandbox Code Playgroud)

请注意,func_get_args()将返回传递给函数的所有参数,而不仅仅是签名中没有的参数.另请注意,您在签名中定义的任何参数都被认为是必需的,如果不存在,PHP将引发警告.

如果您只想获取剩余的参数并确定在运行时,您可以使用ReflectionFunction API来读取签名中的参数数量以及array_slice仅包含其他参数的完整参数列表,例如

function my_func($foo, $bar)
{
    $rf = new ReflectionFunction(__FUNCTION__);
    $splat = array_slice(func_get_args(), $rf->getNumberOfParameters());
    return array($foo, $bar, $splat);
}
Run Code Online (Sandbox Code Playgroud)

为什么有人会想要仅仅使用func_get_args()它超出我,但它会工作.更直接的是以下列任何方式访问参数:

echo $foo;
echo func_get_arg(0); // same as $foo
$arguments = func_get_args();
echo $arguments[0]; // same as $foo too
Run Code Online (Sandbox Code Playgroud)

如果需要记录变量函数参数,PHPDoc建议使用

/**
 * @param Mixed $foo Required
 * @param Mixed $bar Required
 * @param Mixed, ... Optional Unlimited variable number of arguments
 * @return Array
 */
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.