PHP-based reference explanation-reference transfer and return reference transfer
A variable can be passed to the function through reference, so that the function can modify the value of its parameter. Syntax:
Note that there is no reference symbol when calling a function-only in the function definition. Function definition is enough to make parameters pass through references correctly. In the latest PHP version, if you use & in foo (& $ a);, you will receive a warning that "Call-time pass-by-reference" is out of date.
The following content can be passed through reference:
Variable, such as foo ($)
New statement, such as foo (new foobar ())
Reference returned from the function, for example:
No other expressions can be passed through references, and the results are undefined. For example, the example passed by reference below is invalid:
These conditions are available in PHP 4.0.4 and later versions.
Reference return
The return value of the reference is used when you want to use the function to find the variable on which the reference should be bound. Do not use return references to increase performance. the engine is smart enough for optimization. A reference is returned only when there are reasonable technical reasons! To return a reference, use this syntax:
value; } } $obj = new foo; $myValue = &$obj->getValue(); // $myValue is a reference to $obj->value, which is 42. $obj->value = 2; echo $myValue; // prints the new value of $obj->value, i.e. 2.?>
In this example, the attributes of the objects returned by the getValue function will be assigned, rather than being copied, just like the reference syntax.
Note: Unlike parameter transfer, the & symbol must be used here to indicate that a reference is returned instead of a normal copy. it also indicates that $ myValue is bound as a reference, instead of assigning values normally.
Note: If you try to return the reference from the function like this: return ($ this-> value);, this will not work because you are trying to return the result of an expression rather than a referenced variable. Only variables can be referenced from function return-no other method. If the code tries to return the result of a dynamic expression or new operator, an E_NOTICE error will be issued since PHP 4.4.0 and PHP 5.1.0.