PHP方法()->;方法()->;方法()->;
我如何在PHP中创建类,它将像codeIgniter中的DB类一样工作 我可以这样使用这个类: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
$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 ) ;