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

4

请记住,您可以更改您接受的答案 :P - Gabriel Sosa
1
Gabriel Sosa是正确的。链接应该通过方法返回值(即return $this;)来完成,使用$this->method1()->method2(),而不是将对象分配给属性并使用$this->obj1->obj2,这在大多数情况下是不必要的,并且可能会导致混淆。 - Tres
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

?>


我可以补充一下,这是一种非常优雅的编码方式。 - Tres
非常有趣的编码。唯一的缺点似乎是它不能跨类“记录”方法调用 - 如 $url->anchor()。不过,我相信总有一天我会找到这种编码风格的用途。谢谢.. :-) - Kristoffer Bohmann

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

Anti Veeranna的解决方案符合我的目的——使代码易读、自我记录(当方法在类之间调用时)。 - Kristoffer Bohmann

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

这个问题有点令人困惑,但我认为这正是他不想做的事情 :) - Anti Veeranna
没错。目的是在调用其他类中的方法时“自我记录”。好的写法:$url->anchor()。坏的写法:$this->anchor()。 :-) - Kristoffer Bohmann

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接