Hacking with PHP has been updated for PHP 7 - click here! >>

Deferencing object return values

This is a bit of an odd section - one that doesn't really fit anywhere, but definitely has to go somewhere . Dereferencing object return values is a fancy way of saying that if you call a function that returns an object, you can treat the return value of that function as an object from the calling line and access it directly. Did that clear things up? Good, now onto the next topic...

Just kidding - I realise that wasn't the clearest explanation! This code should explain:

    $lassie = new dog();
    $collar = $lassie->getCollar();
    echo $collar->Name;

    $poppy = new dog();
    echo $poppy->getCollar()->Name;

In the first example, we need to call getCollar() and save the returned value into $collar, before echoing out the Name variable of $collar. In the second example, we use the return value from getCollar() immediately from within the same line of code, and echo out Name without an intermediate variable like $collar.

A curious thing about this functionality is that you if you ask a group of people which of the two blocks of code is easier to read, it will split about 50/50 into two groups of people who swear that one way is easier and that the other way is simply impossible to read. So, if you thought the first way was better (or vice versa, like me), do at least keep it in mind that not everyone will agree!

Author's Note: Please remember that, for now at least, return value dereferencing only applies to objects. If you have a function someFunc() that returns an array, for example, you cannot use $obj->someFunc()[3] to access an element in the return value - you need to store the return value in another variable, then access it. This might be added in the future, but the syntax does look a little clumsy.


If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: The Object-Oriented Website >>

Previous chapter: Interfaces

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.