2012-10-02 57 views
0

我有這樣的代碼:PHP OOP鏈接方法

class one{ 
    public $instance; 

    function instance(){ 
     $this->instance = 'instance was created'; 
    } 

    function execute(){ 
     $this->instance .= "and something happened"; 
    } 
} 

$class = new one; 

$class->instance(); 
$class->execute(); 

echo $class->instance; 

它做什麼,我希望它做的,但我怎麼可以連的行動,比如我怎麼能在一行調用這些函數:

$class->instance()->execute(); 

,我知道這是可以做到這樣的:

one::instance()->execute(); 

但在這種情況下,我需要有靜態函數這使得事情變得複雜,我需要這些東西

回答

2

一些解釋爲了鏈接工作,你需要從每個方法返回$this你想成爲可鏈接:

class one{ 
    public $instance; 

    function instance(){ 
     $this->instance = 'instance was created'; 
     return $this; 
    } 

    function execute(){ 
     $this->instance .= "and something happened"; 
     return $this; 
    } 
} 

而且,這是一個壞主意爲屬性賦予與方法相同的名稱。這對解析器來說可能是毫不含糊的,但對開發人員來說卻是令人困惑的。

0

你需要在你的函數結束返回的實例:

class one{ 
    public $instance; 

    function instance(){ 
     $this->instance = 'instance was created'; 
     return $this; 
    } 

    function execute(){ 
     $this->instance .= "and something happened"; 
     return $this; 
    } 
} 

然後你就可以把它們連。

順便說一句,這可能只是示例代碼,但您instance功能實際上並不創建實例;)

0

$類 - >實例() - >執行();

應該可以工作,但你需要在你的方法中返回你的值。

1

鏈接的一般方法是將任何需要鏈接的方法返回$this作爲return。所以,對於你的代碼,它可能看起來像這樣。

class one{ 
    public $instance; 

    function instance(){ 
     $this->instance = 'instance was created'; 
     return $this; 
    } 

    function execute(){ 
     $this->instance .= "and something happened"; 
     return $this; 
    } 
} 

所以你冷做:

$one = new one; 
$one->instance()->execute(); // would set one::instance to 'instance was createdand something happened' 
$one->instance()->instance()->instance(); // would set one::instance to 'instance was created'; 
$one->instance()->execute()->execute();/would set one::instance to 'instance was createdand something happenedand something happened'