4

如何在 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

4

3 回答 3

7

实际上这个问题是模棱两可的......对我来说这个@Geo的答案是正确的。

你(@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

?>

于 2009-09-15T02:56:55.800 回答
5

只要您的 $myclass 有一个成员/属性本身就是一个实例,它就会像那样工作。

class foo {
   public $bar;
}

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

$myclass = new foo();
$myclass->bar = new bar();
print $myclass->bar->hello();
于 2009-09-06T11:28:12.180 回答
1

为了像这样链接函数调用,通常你从函数中返回 self (或 this )。

于 2009-09-06T11:30:16.800 回答