Questions And Answers

More Tutorials

PHP by Reference

Occasionally there comes time for you to implicitly return-by-reference.

Returning by reference is useful when you want to use a function to find to which variable a reference should be bound. Do not use return-by-reference to increase performance. The engine will automatically optimize this on its own. Only return references when you have a valid technical reason to do so.

There are many different forms return by reference can take, including the following example:

function parent(&$var) {
 echo $var;
 $var = "updated";
function &child() {
 static $a = "test";
 return $a;
parent(child()); // returns "test"
parent(child()); // returns "updated"

Return by reference is not only limited to function references. You also have the ability to implicitly call the function:

function &myFunction() {
 static $a = 'foo';
 return $a;
$bar = &myFunction();
$bar = "updated"
echo myFunction();

You cannot directly reference a function call, it has to be assigned to a variable before harnessing it. To see how that
works, simply try echo &myFunction();.

  • You are required to specify a reference (&) in both places you intend on using it. That means, for your function definition function &myFunction() {...) and in the calling reference (function callFunction(&$variable) {... or &myFunction();).

  • You can only return a variable by reference. Hence the instantiation of $a in the example above. This means you can not return an expression, otherwise an E_NOTICE PHP error will be generated (Notice: Only variable references should be returned by reference in ......)
  • .
  • Return by reference does have legitimate use cases, but I should warn that they should be used sparingly, only after exploring all other potential options of achieving the same goal.

  • Conclusion

    In this page (written and validated by ) you learned about PHP by Reference . What's Next? If you are interested in completing PHP tutorial, your next topic will be learning about: PHP Pass by Reference.

    Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

    Share On:

    Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.