Search code examples
phpoopchaining

How to chain objects of mixed types in PHP5


I'd like to chain-reference a string property like this:

echo($object1->object2->stringProperty);

But that yields this error:

Catchable fatal error: Object of class [object 2's type] could not be converted to string

Can I make this work by forcing a typecast somewhere in there? It works to use an intermediate variable for the middle object, but that adds unfortunate cruft:

class foo {
    public $bar;
}

class bar {
    public $title;
}

// Initialize the example.
$myBar = new bar();
$myFoo = new foo();
$myFoo->bar = $myBar;
$myBar->title = "fubar";

// Using an intermediate object works.
$temp = $myFoo->bar;
echo("$temp->title<br />");

// Using a direct reference raises a fatal error.
echo("$myFoo->bar->title<br />");

Solution

  • Either remove the quotes:

    echo $myFoo->bar->title . "<br />";
    

    or place in braces (also known as complex syntax):

    echo "{$myFoo->bar->title}<br />";