2016-08-16 60 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();