2016-08-16 5 views
-7

こんにちは私はこのようなコードを作っています...これを実装する方法の例を教えてもらえますか?PHP OOP aboutクラス

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

ありがとうございました。

+0

あなたはこのhttp://www.tutorialspoint.com/php/php_object_oriented.htm –

+1

見上げて "流れるようなインターフェイス" を参照してくださいOOPSの概念を学ぶ必要がありますが、:

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

上記エコーします基本的に '$ this'を返すために' firstMethod() 'が必要です –

+1

あなたの質問にもっと具体的にする必要があります[どうすればいい質問ができますか?](http://stackoverflow.com/help/how-to-あなたは**クラス**に対処する方法を学びたいですか?それらを使用する方法?あるいは、同じ行で複数のメソッドを呼び出す方法は? –

答えて

3

を持っています。 $ theclass変数にメソッドを適用するには、クラスのインスタンスである必要があります。のは、それを定義してみましょう:

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別の方法$theclassvariable->firstMethod->secondMethod()、上の方法を適用したい場合。これを行うには、それぞれの方法で$this(オブジェクト)を返す必要があります。これは、PHP(および他の言語)で連鎖可能なメソッドを作成する方法です。

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

どうすれば他のクラスの他のメソッドをチェーンしたいのですか?それは可能ですか?ex:$ 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();