在对象中通过引用存储参数的动态数量,以便稍后更改


Store dynamic number of arguments by reference in object, to be changed later

好的,我有一个独特的问题。我有一个函数正在被调用,我需要这个与它已经被调用的方式一起工作。我把一些代码放在一起,尽可能接近答案:

class some_class {
    private $_some_stuff = array();
    public function some_method()
    {
        $args = func_get_args();
        foreach($args as &$name)
        {
            $this->_some_stuff[] =& $name;
        }
    }
    public function other_method()
    {
        for ($i = 0; $i < count($this->_some_stuff); $i++)
        {
            $this->_some_stuff[$i] = 'somevalue';
        }
    }
}

$some_object = new some_class();
$one = 'firstever';
$two = 'secondever';
$some_object->some_method(&$one, &$two);
$some_object->other_method(&$one, &$two);
echo $one;
echo '<br>...<br>';
echo $two;

我需要$one$two在最后输出"一些值"。如果不清楚,我需要能够通过引用将一些值传递到对象的一个方法中,然后让对象的另一个方法仍然能够访问这些值;

我相信这是可行的:

public function some_method()
{
    $backtrace = debug_backtrace();
    $args = $backtrace[0]['args'];
    foreach($args as &$name)
    {
        $this->_some_stuff[] =& $name;
    }
}

,但正如其他人所说,"它是如何被调用的"是通过引用调用时间传递的,这是不赞成的

调用时引用传递已被弃用,因为结果是硬代码。尝试重新组织应用程序

您不能使用func_get_args(),因为正如手册所说,它不会通过引用返回:

返回一个数组,其中每个元素都是当前用户定义函数的参数列表中对应成员的副本。

从测试看来,func_get_arg()具有相同的行为。

指示PHP通过引用函数来提供参数的唯一方法是使用函数参数列表中的&。因为你没有参数列表,你想要的是不可能的。

它也是丑陋的!PHP中的引用传递充满了问题,应该避免使用。

但是,如果您愿意更改您的some_method()签名,您可以执行以下操作:

class some_class {
    private $_some_stuff = array();
    public function some_method(&$args)  // notice we accept a single arg by reference
    {
        foreach ($args as &$arg) {
            $this->_some_stuff[] =& $arg;
        }
    }
    public function other_method()
    {
        for ($i = 0; $i < count($this->_some_stuff); $i++)
        {
            $this->_some_stuff[$i] = 'somevalue';
        }
    }
}

$some_object = new some_class();
$one = 'firstever';
$two = 'secondever';
// now whenever you call this method, use this EXACT PATTERN:
$args = array(&$one, &$two); // this MUST be its own statement on its own line, and MUST have referenced elements!
$some_object->some_method($args); // CANNOT do $some_object->some_method(array(&$one, &$two)); !!!
$some_object->other_method();
var_dump($some_object);
var_dump($args);
var_dump($one);
var_dump($two);

你想做什么就做什么。

还请注意,调用时引用传递(thefunc(&$foo);)已贬值,可能不再工作。