PHP OOP 如何实现这样写法?(new MySQL())->field()->where()->select()


在很多MVC框架,比如ThinkPHP,Laravel 中看到这样的写法。
但如何写类才可以实现这样的功能?


 $s = (new MySql())
    ->field('*')
    ->table('Test')
    ->where(array('id' => 1))
    ->select();
var_dump($s);


 //报错 Fatal error: Call to undefined method MySql::field() in 
class MySql
{

    public function select()
    {

    }
}

oop php

JrSeven 10 years, 3 months ago

如果你看过jQuery的源码,就知道了,return this就能chain起来,同理在php中,你需要return $this;

young89 answered 10 years, 3 months ago

链式操作,现在是可以的,我的版本是5.2.17

ks135 answered 10 years, 3 months ago


 class Test{

    public function aaa(){
        echo "aaa";
        return $this;
    }

    public function bbb(){
        echo "bbb";
        return $this;
    }

    public function ccc(){
        echo "ccc";
        return $this;
    }
}

$test = new Test();

$test->aaa()->bbb()->ccc();

l华呖呖哩哩 answered 10 years, 3 months ago

Your Answer