Home > database >  PHP - How to change reference of a function's pointer parameter from the definition
PHP - How to change reference of a function's pointer parameter from the definition

Time:02-03

I'm using PHP 7.4. From the function call, I need to change the reference of a variable passed to it by reference. This is the simplified version of my code to make it clear and more focus on the problem.

function f(&$p){
    $p['x'] = [];
    $p = &$p['x'];
    //$p represents $a['x'] here
}
$a = [];
$p = &$a;
f($p);
//$p revert to $a here
$p['y'] = 3;
echo json_encode($a);

I expected the function to change the reference of variable $p from pointing to $a to $a['x']. Within the definition scope, it did. But the reference reverted back to $a after the call.

So from the above code, instead of this {"x" : {"y" : 3}}, I get this {"x" : {}, "y" : 3} as the result.

I assume that a function's pointer parameter can only be used to change the value not the reference. But is there any way to do the same for a reference considering that reference is also a type of value?.

CodePudding user response:

I realized what you needed, your solution is this.

function &f(&$p){
    $p['x'] = [];
    $p = &$p['x'];
    return $p;
}
$a = [];
$p = &$a;
$p = &f($p);
$p['y'] = 3;
echo json_encode($a);
  •  Tags:  
  • Related