在PHP中杀死方法链

geo*_*oot 2 php methods method-chaining

嗨我有一个像PHP的方法链

<?php
auth::('username') -> is_logged() -> doSomething();
//execute something
?>
Run Code Online (Sandbox Code Playgroud)

我想做的是如果用户没有登录,那么不调用doSomething()函数.一种方法是取消设置$ this,但这将产生一个错误ID,有任何其他方式来做到这一点.此外,我不能使用die(),因为它会停止编译器,并防止执行后编写的代码.最好的方法是什么,最好没有任何警告或错误,同时由于与该类相关的大量功能而尽可能少地进行更改.

Max*_*sky 6

返回NullObject,它将提供doSomething的空实现

在PHP中,您只需要提供魔术__call()方法,因此任何函数调用都将通过.

class NullObject {
    public function __call($name, $arguments) {
        return $this;
    }
}
Run Code Online (Sandbox Code Playgroud)

要在课堂上使用它:

public function is_logged() {
    if ($this->user_is_logged()) {
        return $this;
    } else {
        return new NullObject;
    }
}
Run Code Online (Sandbox Code Playgroud)