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

2020-02-06 09:24发布

问题:

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

回答1:

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();


回答2:

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

?>



回答3:

In order to chain function calls like that, usually you return self ( or this ) from the function.