简体   繁体   中英

PHP Pass by reference confusion

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.

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM