2014-02-21 3 views
0

PHP로 클래스를 생성하려면 어떻게해야합니까? PHP 클래스는 codeIgniter에서 DB 클래스처럼 작동합니까?PHP 메서드() -> method() -> method() ->

나는 그런 방식으로이 클래스를 사용할 수 있습니다

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

그 같은 :

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

감사합니다. 당신의 방법에서

+0

. 구현이 쉽지만 언제나 좋은 연습으로 간주되지는 않기 때문에 필요하다고 확신해야합니다. http://ocramius.github.io/blog/fluent-interfaces-are-evil/ –

답변

8

현재 개체를 반환 :

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

을 그리고 그런데, 그것은 method chaining를 불렀다.

5

이렇게 연결하는 것은 실제로 매우 간단합니다. 각 메소드는 $this을 리턴 할뿐입니다.

4

method chaining을 읽으십시오.

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

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

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

는 '체인'을 사용하려면, u는 다음과 같이 클래스의 인스턴스를 반환해야합니다 : 유창 인터페이스/메소드 체인이라고

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) ; 
관련 문제