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

标签 php class oop chaining

如何在 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) 说的可能是 composition

这是我的例子:

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

?>

关于php - 如何在 PHP5 : $this->foo->bar->baz() 中链接对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1385429/

相关文章:

javascript - jQuery 自动完成 ajax 请求不显示返回的数据

php - 基于城市和地区的自动完成搜索

oop - 单独使用方法名称解析 MATLAB 类方法句柄

C#继承类型转换错误

php - 使用 PHP 创建桌面应用程序

php 创建文件并作为附件发送而不实际创建文件

class - 非托管 var 作为托管类 c++ 的成员

class - 如何创建 coffeescript 单例子类

java - 向类型安全的异构容器中插入对象时,为什么需要类引用?

python - 确保 Python 中不存在 __init__ 函数