【问题标题】:Get argument values as reference in PHP [duplicate]在PHP中获取参数值作为参考[重复]
【发布时间】:2013-01-03 09:11:12
【问题描述】:

可能重复:
How can arguments to variadic functions be passed by reference in PHP?

我需要从 methodfunction 的参数中获取值。我知道我可以用func_get_args() 做到这一点。但我真的需要通过引用来获取论点。有什么办法吗?

我目前有这个:

<?php
class Test
{
    function someFunc ( $arg1, $arg2 )
    {
        print_r ( func_get_args() );
    }
}

$t = new Test();
$t->someFunc('a1', 'a2');
?>

在我的真实代码中,参数值被传递给另一个class-&gt;method()。在那里我希望能够更改参数值。如果我能得到这些值作为参考,这将是可能的。

有解决办法吗?

【问题讨论】:

标签: php reference


【解决方案1】:

现在没有什么能阻止你 .. 只需将其设为 variable instead,否则 PHP 将返回 Fatal error: Cannot pass parameter 1 by reference

class Test {

    function someFunc(&$arg1, &$arg2) {
        var_dump(func_get_args());

        $arg1 = strtoupper($arg1);
        $arg2 = strtoupper($arg2);
    }
}

echo "<pre>";

$arg1 = "a1";
$arg2 = "ar2";
$t = new Test();
$t->someFunc($arg1, $arg2);

var_dump($arg1, $arg2);

输出

array (size=2)
  0 => string 'a1' (length=2)
  1 => string 'ar2' (length=3)

string 'A1' (length=2) // modified
string 'AR2' (length=3) // modified

【讨论】:

    【解决方案2】:
        <?php
        class Test
        {
            function someFunc ( &$arg1, &$arg2)
            {
    //    used the variable as per you want it....
            }
        }
    
        $t = new Test();
        $t->someFunc('a1', 'a2');
        ?>
    
    
        You have to add & to the arguement so that it can be used as reference...
    

    【讨论】:

      猜你喜欢
      • 2017-09-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-05
      • 1970-01-01
      • 2023-03-28
      • 2018-10-01
      • 1970-01-01
      • 2015-09-04
      相关资源
      最近更新 更多