PHP Pass by reference confusion

大兔子大兔子 提交于 2020-01-01 11:05:33

问题


To cut a long story short I have the following function as part of my framework:

public function use_parameters()
{
    $parameters = func_get_args();

    $stack = debug_backtrace();

    foreach($stack[0]['args'] as $key => &$parameter)
    {
        $parameter = array_shift($this->parameter_values);
    }
}

Where $this->parameter_values = array('value1', 'value2', 'value3', 'value4', 'value5', ...);

Which is used in the following context:

$instance->use_parameters(&$foo, &$bah);

Assigning:

$foo = 'value1';
$bah = 'value2';

Calling it again

$instance->use_parameters(&$something); 

Will set

$something = 'value3'

and so on.

As of 5.3 it would return a 'Deprecated: Call-time pass-by-reference has been deprecated' warning. In an effort to conform to the 5.3 way of working I removed the &'s resulting in:

$instance->use_parameters($foo, $bah);

This unfortunately has caused the arguments not to be set and I'm struggling to come up with a solution.

For what its worth I'm running PHP v5.3.3-7 on Apache/2.2.16 (Debian)

Any help would be greatly appreciated.


回答1:


You can't do that in PHP and you are abusing the concept of references. You have to specify the reference arguments explicitly, albeit with default values. However, you don't want to use NULL as a default as this is what an unassigned reference variable will be set to. So you need to define some constant that you know is not going to be used as a parameter, and now the code will look something like

    const dummy="^^missing^^";

    public function use_parameters(&$a, &$b=self::dummy, &$c=self::dummy ) {
        $a=array_shift($this->parameter_values);
        if($b!==self::dummy) $b=array_shift($this->parameter_values);
        if($c!==self::dummy) $c=array_shift($this->parameter_values);
        # add $d,$e,$f,... as required to a sensible max number
    }

Note that because you are using references properly, you don't need the debug_backtrace() botch.




回答2:


You can't do that in PHP 5 or ... as you've seen you can, but it's deprecated and raises warnings. You'll have to either have a predefined max count of function arguments or use an array:

public function use_parameters(&$arg1, &$arg2 = NULL, &$arg3 = NULL)
{
    // if ($arg2 !== NULL)
    // if ($arg3 !== NULL)
}

$parameters = array(0 => &$foo, 1 => &$bah);

public function use_parameters($args)
{
    // Handle the array elements
}


来源:https://stackoverflow.com/questions/11360810/php-pass-by-reference-confusion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!