2016-08-16 57 views
-7

嗨,我想做一個這樣的代碼...你能給我一個例子如何實現這個?關於類的PHP OOP

$theclassvariable = new Myclass(); 
$theclassvariable->firstMethod()->secondMethod($param,$param); 

非常感謝。

+0

你應該學會OOPS的概念看到這個http://www.tutorialspoint.com/php/php_object_oriented.htm –

+1

查找 「流暢接口」,但基本上你需要你的'firstMethod()'返回'$ this' –

+1

你需要對你的問題更具體一點[我如何問一個好問題?](http://stackoverflow.com/help/how-to-問)你想學習如何處理**班**?如何使用它們?或者,也許,如何在同一行中調用多個方法? –

回答

3

這就是所謂的可鏈接方法的實例。爲了在$ theclassvariable上應用一個方法,它需要是一個類的實例。讓我們來定義它:

class myClass { 

    public function __construct() 
    { 
     echo 'a new instance has been created!<br />'; 
    } 

    public function firstMethod() 
    { 
     echo 'hey there that\'s the first method!<br />'; 
     return $this; 
    } 

    public function secondMethod($first, $second) 
    { 
     echo $first + $second; 
     return $this; 
    } 
} 

$theclassvariable = new myClass(); 

如果你想在另一個方法$theclassvariable->firstMethod->secondMethod()適用的方法,$theclassvariable->->firstMethod必須是一個對象了。爲了做到這一點,你需要在每種方法中返回$this(對象)。這就是你如何在PHP(和其他語言中)中創建可鏈接的方法。

$theclassvariable->firstMethod()->secondMethod(1, 1); 

以上會迴應:

a new instance has been created! 
hey there that's the first method! 
2 
+0

如果我想鏈接其他類的其他方法,可以如何?例如:$ myclassvariable-> firstmenthod() - > secondmethodfromotherclass(); –

+0

如果要將方法應用於* something *,則此* something *必須是已定義該方法的類的實例 – Ivan

2

有類裏面的函數返回類

class Foo{ 

    public function a(){ 
     // Do Stuff 
     return $this; 
    } 

    public function b(){ 
     // Do Stuff 
     return $this; 
    } 

} 

$foo = new Foo(); 
$foo->a()->b();