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

时间:2011-12-04 00:10:01

标签: php pass-by-reference

好的我有一个独特的问题。我有一个函数被调用,我需要它来处理它已被调用的方式。我已经汇总了一些显示尽可能接近答案的代码:

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来输出'somevalue'。如果不清楚,我需要能够通过引用将一些值传递给对象的一个​​方法,然后让对象的单独方法仍然能够访问这些值;

3 个答案:

答案 0 :(得分:1)

不推荐使用call-time pass-by-reference,因为结果是硬代码。 尝试重新组织您的应用程序

答案 1 :(得分:1)

您无法使用func_get_args(),因为手册中说它不会通过引用返回:

  

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

从测试中可以看出func_get_arg()具有相同的行为。

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

它还 hideous ! PHP中的传递引用是fraught with problems,应该避免使用。

但是,如果您愿意更改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);)已弃用,可能不再有效。

答案 2 :(得分:1)

我相信这有效:

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

但正如其他人所说的那样,“它是如何调用的”是通过引用传递的调用时间,不推荐使用

相关问题