Call time pass by reference was removed in PHP 5.4. But I have a special case where it seems to be still available in PHP 8 (tried it here: www.w3schools.com):
$myVar = "original";
testFunc([$myVar]);
echo "Variable value: $myVar<br>"; // Output is: "Variable value: original"
testFunc([&$myVar]);
echo "Variable value: $myVar<br>"; // Output is: "Variable value: changed"
testFunc([&$undefinedVar]);
echo "Variable value: $undefinedVar<br>"; // Output is: "Variable value: changed"
testFunc([$undefinedVar_2]);
echo "Variable value: $undefinedVar_2<br>"; // Output is: "Variable value: "
function testFunc( array $arr ) : void
{
if ( !is_array($arr)
|| count($arr) == 0 )
return;
$arr[0] = 'changed';
}
Additionally, this way I can get a C#
like parameter out
functionality.
Maybe I am misunderstanding something.
Question:
How could I identify within "testFunc" if $arr[0]
was passed by reference or normally?
Alternative question (for people who are searching this topic):
Check if variable was passed by reference.
2
Answers
The code by @Foobar pointed me to the right direction. I am using the output of
var_dump
to analyze it and create a data structure out of it:This is not call-time pass by reference. The parameter to the function is a PHP array, which is passed by value.
However, individual elements of PHP arrays can be references, and the new by-value array will copy over the reference, not the value it points to. As the PHP manual puts it:
To see more clearly, let’s look at an example with no functions involved:
Output:
You do not need any hacks to achieve an out parameter. Pass-by-reference is still fully supported, it’s just the responsibility of the function to say that it uses it, not the code that calls the function.
C#
out
parameters also need to be part of the function definition:The only difference is that PHP only has an equivalent for
ref
, notout
andin
: