如何用php实现类似js的链式操作?

$str = new str();
//类似这种链式操作,如何实现?
$str->str()->length();
阅读 3.6k
5 个回答
Class MyClass {

    public function doWork() {
        echo "work done\n";
        return $this;
    }
    
    public function doAnotherWork() {
        echo "another work done\n";
        return $this;
    }

}
(new MyClass())->doWork()->doAnotherWork();

ThinkPHP的数据库操作就支持这种方式,你可以看看他的实现方法。

很简单,返回对象即可。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题