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

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-06 20:41:54
Original
1168 people have browsed it

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

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

    public function select()
    {

    }
}
</code>
Copy after login
Copy after login

回复内容:

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

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

    public function select()
    {

    }
}
</code>
Copy after login
Copy after login

如果你看过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>
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template