PHP, returns class as object
I am testing a way to write PHP as js and I am wondering if this is possible.
If I have a function A, B in class C.
Class C{
function A(){
}
function B(){
}
}
$D = new C;
$D->A()->B(); // <- Is this possible and how??
In Js, we can just write like D.A().B();
I tried return $this
inside function A()
, didn't work.
Thanks a lot for your advice.
+3
source to share
4 answers
Quite simply, you have a series of mutator methods that return the original (or other) objects, so you can keep calling functions.
<?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();
This outputs "ab"
Returning $this
inside a function allows you to call another function with the same object as jQuery.
+3
source to share