【问题标题】:Best way to emulate Ruby "splat" operator in PHP function signatures [Method overloading]在 PHP 函数签名中模拟 Ruby“splat”运算符的最佳方法 [方法重载]
【发布时间】:2010-08-25 21:49:12
【问题描述】:

在 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]

在 PHP (5.3) 中

function my_func($foo, $bar, ... ){
  #...
}

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

【问题讨论】:

  • 看看 func_get_args()

标签: php ruby overloading


【解决方案1】:

another question复制我与此相关的答案:

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

例子:

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

【讨论】:

    【解决方案2】:

    试试

    • func_get_args — 返回一个包含函数参数列表的数组

    您的 Ruby 代码段的 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) );
    

    或者只是

    function my_func($foo, $bar)
    {
        return array($foo , $bar , array_slice(func_get_args(), 2));
    }
    

    给予

    Array
    (
        [0] => 1
        [1] => 2
        [2] => Array
            (
                [0] => 3
                [1] => 4
                [2] => 5
                [3] => 6
            )
    )
    

    请注意,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);
    }
    

    为什么有人会想要仅仅使用func_get_args() 而不是我,但它会起作用。更直接的是通过以下任何方式访问参数:

    echo $foo;
    echo func_get_arg(0); // same as $foo
    $arguments = func_get_args();
    echo $arguments[0]; // same as $foo too
    

    如果您需要记录变量函数参数,PHPDoc suggest to use

    /**
     * @param Mixed $foo Required
     * @param Mixed $bar Required
     * @param Mixed, ... Optional Unlimited variable number of arguments
     * @return Array
     */
    

    希望对您有所帮助。

    【讨论】:

    • Gordon,splat 将所有重载的参数收集到一个数组中。我担心 PHP 将不得不自己去获得这种类型的功能......
    • 你甚至不需要 $foo 和 $bar 在函数定义中,除了“文档”目的 - 函数 my_func() 就足够了 - 尽管如果 $foo 和 $bar 在函数中定义它们可以在函数代码中被引用。
    • @macek 好吧,PHP 不具备仅收集重载参数的功能,但func_get_args 将包含传递给独立于其签名的函数的任何参数。在上述函数中,$foo$bar 使这两个必需参数。如果您不提供它们,PHP 将引发错误。在函数内部是$foo is func_get_arg(0) is func_get_args()[0]
    • @macek 只是使用 list($foo, $baz, $baz) = array() 将结果数组拆分为您想要的变量。 us3.php.net/list另外,当你不投掷某人选择的平台时,你一定会得到更多有用的答案。
    • @Alan,我不打算投掷 PHP;我用它所有的时间。 PHP 只是不太适合元编程。
    猜你喜欢
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 2016-09-27
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    • 2023-04-08
    相关资源
    最近更新 更多