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

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

WBOY
WBOYOriginal
2016-06-06 20:41:541103browse

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

<code>$s = (new MySql())
    ->field('*')
    ->table('Test')
    ->where(array('id' => 1))
    ->select();
var_dump($s);
</code>
<code>//报错 Fatal error: Call to undefined method MySql::field() in 
class MySql
{

    public function select()
    {

    }
}
</code>

回复内容:

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

<code>$s = (new MySql())
    ->field('*')
    ->table('Test')
    ->where(array('id' => 1))
    ->select();
var_dump($s);
</code>
<code>//报错 Fatal error: Call to undefined method MySql::field() in 
class MySql
{

    public function select()
    {

    }
}
</code>

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

<code>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();
</code>

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn