Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto chain objects in PHP5: $this->foo->bar->baz()

How do I make chained objects in PHP5 classes? Examples:

$myclass->foo->bar->baz();
$this->foo->bar->baz();
Not: $myclass->foo()->bar()->baz();

See also:
http://www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html

like image 530
Kristoffer Bohmann Avatar asked Dec 13 '22 02:12

Kristoffer Bohmann


2 Answers

actually this questions is ambiguous.... for me this @Geo's answer is right one.

What you (@Anti) says could be composition

This is my example for this:

<?php
class Greeting {
    private $what;
    private $who;


    public function say($what) {
        $this->what = $what;
        return $this;
    }

    public function to($who) {
        $this->who = $who;
        return $this;
    }

    public function __toString() {
        return sprintf("%s %s\n", $this->what, $this->who);
    }

}

$greeting = new Greeting();
echo $greeting->say('hola')->to('gabriel'); // will print: hola gabriel

?>

like image 154
Gabriel Sosa Avatar answered Dec 24 '22 16:12

Gabriel Sosa


As long as your $myclass has a member/property that is an instance itself it will work just like that.

class foo {
   public $bar;
}

class bar {
    public function hello() {
       return "hello world";
    }
}

$myclass = new foo();
$myclass->bar = new bar();
print $myclass->bar->hello();
like image 35
Anti Veeranna Avatar answered Dec 24 '22 18:12

Anti Veeranna