0

I found the following code and I don't get why it works :

function test(&$argtest) {
    $argtest = 'ok';
}

test($a);

//$a now exists, and is equal to 'ok'.

$a is not defined before calling the function, yet the code works and now $a exists in the global scope. I would have expected an error, since $a is not defined prior to calling the function.

Basically the code I was looking utilizes this approach to declare\init some variables in the global scope.

This only works if the argument of the function is passed by reference.

Nite
  • 107
  • 1
  • 7
  • @0stone0 I understand what the & does, the question was about the fact that the variable is not defined prior to calling the function. – Nite Jan 19 '22 at 15:59
  • Not sure what your question is if you fully understand `&`. As your example shows, it's defined, so to answer the title's question: Yes. – 0stone0 Jan 19 '22 at 16:01
  • 2
    There is [a section in the PHP manual titled "References Explained"](https://www.php.net/manual/en/language.references.php) which is definitely worth reading to avoid any misconceptions about what references are and aren't. – IMSoP Jan 19 '22 at 16:02
  • 1
    @0stone0 There really is no need for hostility, I did read the PHP doc page about function arguments by reference, and I could not find an answer there. I'll definitely check the "References Explained" page linked by IMSoP , which I didnt know about. – Nite Jan 19 '22 at 16:11

0 Answers0