Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Dereferencing Object Return Values

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. For example:

    $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 property 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 property like $collar.

Warning

For now at least, return value dereferencing only applies to objects. If you have a function someFunc() that returns an array, for example, using $obj->someFunc()[3] to access an element in the return value will cause a parse error—you need to store the return value in another property, then access it.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page