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:
In other words, the reference behavior of arrays is defined in an element-by-element basis; the reference behavior of individual elements is dissociated from the reference status of the array container.
To see more clearly, let's look at an example with no functions involved:
$myVar = 42;
// Make an array with a value and a reference
$array = [
'value' => $myVar,
'reference' => &$myVar
];
// Make a copy of the array
$newArray = $array;
// Assigning to the value in the new array works as normal
// - i.e. it doesn't affect the original array or variable
echo "Assign to 'value':\n";
$newArray['value'] = 101;
var_dump($myVar, $array, $newArray);
echo "\n\n";
// Assigning to the reference in the new array follows the reference
// - i.e. it changes the value shared between both arrays and the variable
echo "Assign to 'reference':\n";
$newArray['reference'] = 101;
var_dump($myVar, $array, $newArray);
Output:
Assign to 'value':
int(42)
array(2) {
["value"]=>
int(42)
["reference"]=>
&int(42)
}
array(2) {
["value"]=>
int(101)
["reference"]=>
&int(42)
}
Assign to 'reference':
int(101)
array(2) {
["value"]=>
int(42)
["reference"]=>
&int(101)
}
array(2) {
["value"]=>
int(101)
["reference"]=>
&int(101)
}
Additionally, this way I can get a C# like parameter out functionality.
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.
function doSomething(&$output) {
$output = 'I did it!';
}
$output = null;
doSomething($output);
echo $output;
C# out
parameters also need to be part of the function definition:
To use an out
parameter, both the method definition and the calling method must explicitly use the out
keyword.
The only difference is that PHP only has an equivalent for ref
, not out
and in
:
[The out
keyword] is like the ref
keyword, except that ref
requires that the variable be initialized before it is passed.