【问题标题】:PHP Chain with Parent Function带有父函数的 PHP 链
【发布时间】:2016-10-21 16:10:34
【问题描述】:

我想用它自己的父函数链接一个方法。

例子:

class Query
{
    protected $limit;

    /**
     * Returns some third object that isn't in this family.
     * This object represents the results, and also has
     * a first function that gets called in a chain.
     */
    public function get()
    {
        // Do Stuff

        return new /* ... */;
    }

    public function take($amount)
    {
        $this->limit = $amount;

        return $this;
    }
}

class ChildQuery extends Query
{
    protected $singular = false;

    public function get()
    {
        if($this->singular)
            return $this->take(1)->parent::get()->first();

        return parent::get()
    }

    public function singular()
    {
        $this->singular = true;

        return $this;
    }
}

这显然不是完整的功能集,也不起作用,但你明白了。我希望ChildQuery::get 能够在链中调用Query::get

现在,我必须这样做:

public function get()
{
    $this->take(1);

    parent::get()->first();
}

这对我没有吸引力。有什么想法吗?

如果重要的话,我正在运行 PHP 7。

我的最终结果应该是这样的:

$query->singular()->get(); // ($query is a ChildQuery)

【问题讨论】:

    标签: php parent-child php-7 chaining


    【解决方案1】:

    不可能通过对象的公共接口调用父方法(即使它与当前上下文是相同的类/对象)。也请查看https://stackoverflow.com/a/11828729/2833639

    在我看来,您的解决方案是正确的方法。

    题外话:我建议阅读https://ocramius.github.io/blog/fluent-interfaces-are-evil/ 以评估流体界面是否适合您的用例。

    【讨论】:

    • 另外,我并不总是使用 Fluent API,但有时它们非常方便,例如查询(甚至您的相关文章都建议这样做)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多