PHP方法() - >方法() - >方法() - >

时间:2014-02-21 15:27:20

标签: php class methods

如何在PHP中创建类,它将像codeIgniter中的DB类一样工作?

我可以这样使用这个类:

$this->db->select('...');
$this->db->where('...');
$this->db->get('...');

和那样:

$this->db->select('...')->where('...')->get('...')-> .......

感谢。

4 个答案:

答案 0 :(得分:8)

在你的方法中返回你当前的对象:

public function method() {
    // ...
    return $this;
}

顺便说一下,它被称为method chaining

答案 1 :(得分:5)

这样的链接实际上非常简单。您只需让每个方法返回$this

答案 2 :(得分:4)

阅读method chaining

class User
{
   public function first()
   {
       return $this;
   }

   public function second()
   {
       return $this;
   }
}

$user = new User();
$user->first()->second();

答案 3 :(得分:1)

要使用' chaining',你应该返回类的实例,如下所示:

class Sql {

    protected $select ;
    protected $where ;
    protected $order ;

    public function select( $select ) {
        $this->select = $select ;
        //this is the secret
        return $this ;
    }

    public function where( $where ) {
        $this->where = $where ;
        //this is the secret
        return $this ;
    }

    public function order( $order ) {
        $this->order = $order ;
        //this is the secret
        return $this ;
    }

}

$sql = new Sql() ;

$sql->select( "MY_TABLE" )->where( "ID = 10" )->order( "name" ) ;

var_dump( $sql ) ;
相关问题