【问题标题】:PHP OOP about classPHP OOP 关于类
【发布时间】:2016-12-22 12:16:56
【问题描述】:

您好,我想编写这样的代码...您能举个例子说明如何实现吗?

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

非常感谢。

【问题讨论】:

标签: php oop


【解决方案1】:

它被称为可链接的方法。为了在 $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-&gt;firstMethod-&gt;secondMethod() 上应用一个方法,$theclassvariable-&gt;-&gt;firstMethod 也需要是一个对象。为此,您需要在每个方法中返回$this(对象)。这就是您在 PHP(和其他语言......)中创建可链接方法的方式。

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

上面会回显:

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

【讨论】:

  • 如果我想从其他类中链接其他方法怎么样?这可能吗?例如:$myclassvariable->firstmenthod()->secondmethodfromotherclass();
  • 如果你想将方法应用到一个something,这个something必须是定义了该方法的类的一个实例
【解决方案2】:

让类中的函数返回类的实例

class Foo{

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

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

}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-25
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多