0

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?.

6
  • Why would you not just pass $a by reference? what is echo json_encode($p); ? Commented Feb 2, 2022 at 20:46
  • @futureweb to show the example that matches exactly the problem i'm having and passing $a doesn't show it. php.net/manual/en/function.json-encode.php Commented Feb 2, 2022 at 20:54
  • 1
    What has json_encode got to do with it ? you are passing an array by reference &$p which is copied from an array $a then somehow you expect $a to be equal to $p because you say $p = &a you are passing $a by ref to $p then passing $p by ref to the function I don't think this will update $a Commented Feb 2, 2022 at 21:07
  • No of course the result will be ``` {"x" : {}, "y" : 3}``` you set x to an empty array then json_encode it Commented Feb 2, 2022 at 21:11
  • extendsclass.com/php-bin/39aa6f0 see Commented Feb 2, 2022 at 21:12

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

thank you for your answer. actually i need more straight forward solution which doesn't involve reassigning because the parameter is already a pointer. i take your answer for now but it would be nice if you'd update it with better answer later
Actually I agree with your concept, because it is logical and as we know references in 'C' have working as you have described. But PHP blocks the propagation of this assignment $p=&$p['x']; through input parameters between 2 different contexts. I think in PHP, the maximum what we can do in this case with references, is what I wrote.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.