【问题标题】:Return items and method chaining in php在 php 中返回项目和方法链接
【发布时间】:2018-08-31 06:19:57
【问题描述】:

我从 laravel 中注意到的一件事是您可以获取项目并链接功能。这在 laravel 中是如何实现的?我们这里举个例子

从模型中获取数据时,您通常可以执行以下操作 Model::get($id)->toArray();

但如果您只输入Model::get($id),那么它也会返回数据。它是如何实施的?我想制作这样的方法,但我面临的问题是,如果我 return $this 然后我可以执行其他操作但我没有得到任何数据。而如果我返回数据我无法执行链接。

如果有人能给我提供一个例子和一些关于它是如何完成的解释,那就太好了。

【问题讨论】:

标签: php method-chaining


【解决方案1】:

您可以将类用作对象属性,也可以将转换魔术方法与它们关联。在对象属性的类中,您提供链接的方法,当您尝试单独使用该值时,php 会自动调用魔术方法。例如:

假设你有一个类 Foo

class Foo {
    var $value;

    public function __construct($value) {
        $this->value = $value;
    }
    //the magic method __toString is used when you attempt to use the strval of
    // an object instance of this class
    public function __toString() {
        return strval($this->value);
    }
    function toArray(){
        return [
            'value' => $this->value
        ];
    }
}

还有一个类Test

class Test{
    static $foo;
}

如果您初始化Test::$foo = new Foo('var');,那么您可以使用示例中所示的方法链接:

echo Test::$foo; //will echo "var"
print_r(Test::$foo->toArray()); //will echo "Array ( [value] => var )"

此处参考:http://php.net/manual/en/language.oop5.magic.php#object.tostring

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    • 2021-10-07
    相关资源
    最近更新 更多