I am studying for the Zend PHP5 Certification, everything looks good but i can not find real world examples for passing or returning variables my reference.
It would be very nice, if someone has an example when to use this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Let’s say you want to write a function that removes certain values from an array.
You could copy the array and return it. But what if you want to know if anything was removed? Instead you modify the array in-place and return the number of elements removed. So:
If you create a complex structure inside your function you may want to return a reference to it rather than a copy of it. But this is a fairly marginal case because PHP uses copy-on-write (ie its not copied until it’s modified) but there are some valid use cases.
Returning by reference makes more sense when you’re writing a member function of a class. You could return a reference to a data member but this can also break encapsulation.
Lastly, it’s worth noting that all objects are passed and returned by reference by default. Everything else is passed and returned by value.