在PHP5 HOWTO链对象函数:$ this-> foo->酒吧,>巴兹()(H

2019-07-05 03:20发布

如何使连锁目标在PHP5类? 例子:

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

也可以看看:
http://www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html

Answer 1:

只要你的$ MyClass的有一个成员/属性,是一个实例本身它的作用类似。

class foo {
   public $bar;
}

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

$myclass = new foo();
$myclass->bar = new bar();
print $myclass->bar->hello();


Answer 2:

其实这个问题是模糊的....对我来说这@地理的答案是正确的。

你(@Anti)说,可能是成分

这是我在这个例子:

<?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

?>



Answer 3:

为了链函数调用那样,通常你返回从功能自(或本)。



文章来源: Howto chain objects in PHP5: $this->foo->bar->baz()