Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/233.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP方法()->;方法()->;方法()->;_Php_Class_Methods - Fatal编程技术网

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

PHP方法()->;方法()->;方法()->;,php,class,methods,Php,Class,Methods,我如何在PHP中创建类,它将像codeIgniter中的DB类一样工作 我可以这样使用这个类: $this->db->select('...'); $this->db->where('...'); $this->db->get('...'); 就像这样: $this->db->select('...')->where('...')->get('...')-> ....... 谢谢。在您的方法中,返回当前对象: public f

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

我可以这样使用这个类:

$this->db->select('...');
$this->db->where('...');
$this->db->get('...');
就像这样:

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

谢谢。

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

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

顺便说一下,它被称为。

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


要使用“链接”,应返回类的实例,如下所示:

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 ) ;

这称为流畅的接口/方法链接。它很容易实现,但是您必须确保您需要它,因为它并不总是被认为是一种好的实践。
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 ) ;