6.18 Deferencing object return valuesThis is NOT the latest copy of this book; click here for the latest version.
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:
<?php
$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.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|