PHP,返回类作为对象

Mic*_*cah 3 php class function

我正在测试像js一样编写PHP的方式,我想知道这是否可行.

如果说我有A,B在C类中起作用.

Class C{
   function A(){

   }
   function B(){

   }
}
$D = new C;

$D->A()->B(); // <- Is this possible and how??
Run Code Online (Sandbox Code Playgroud)

在Js中,我们可以简单地写 like D.A().B();

我试过return $this里面function A(),没有工作.

非常感谢您的建议.

sha*_*hat 8

您正在寻找的是一个流畅的界面.您可以通过使类方法返回来实现它:

Class C{
   function A(){
        return $this;
   }
   function B(){
        return $this;
   }
}
Run Code Online (Sandbox Code Playgroud)


Lou*_*uer 7

返回$this方法A()实际上是要走的路.请告诉我们那些据说不起作用的代码(该代码可能还有其他错误).


Tec*_*hie 5

它实际上相当简单,您有一系列的 mutator 方法,它们都返回原始(或其他)对象,这样您就可以继续调用函数。

<?php
class fakeString
{
    private $str;
    function __construct()
    {
        $this->str = "";
    }

    function addA()
    {
        $this->str .= "a";
        return $this;
    }

    function addB()
    {
        $this->str .= "b";
        return $this;
    }

    function getStr()
    {
        return $this->str;
    }
}


$a = new fakeString();


echo $a->addA()->addB()->getStr();
Run Code Online (Sandbox Code Playgroud)

这输出“ab”

返回$this函数内部允许您使用同一对象调用另一个函数,就像 jQuery 一样。