我正在测试像js一样编写PHP的方式,我想知道这是否可行。
如果说我有A,B在C类中起作用。
Class C{
function A(){
}
function B(){
}
}
$D = new C;
$D->A()->B(); // <- Is this possible and how??
在Js中,我们可以简单地写like D.A().B();
我在return $this
内尝试function A()
,但没有用。
非常感谢您的建议。
答案 0 :(得分:8)
您正在寻找的是一种流畅的界面。您可以通过让类方法自行返回来实现它:
Class C{
function A(){
return $this;
}
function B(){
return $this;
}
}
答案 1 :(得分:7)
在方法$this
中返回A()
实际上是要走的路。
请告诉我们那些据说不起作用的代码(该代码可能还有其他错误)。
答案 2 :(得分:3)
它非常简单,你有一系列的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();
输出“ab”
在函数内部返回$this
允许您像jQuery一样使用相同的对象调用另一个函数。
答案 3 :(得分:2)
我尝试了它并且有效
<?php
class C
{
public function a() { return $this; }
public function b(){ }
}
$c = new C();
$c->a()->b();
?>