繁体   English   中英

如何在PHP5中链接对象:$ this-> foo-> bar-> baz()

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

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

实际上,这个问题是模棱两可的。...对我来说,@ 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

?>

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

class foo {
   public $bar;
}

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

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

为了链接这样的函数调用,通常需要从函数返回self(或this)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM