PHP, return class as object
Solution 1
What you are looking for is called fluent interface. You can implement it by making your class methods return themselves:
Class C{
function A(){
return $this;
}
function B(){
return $this;
}
}
Solution 2
Returning $this
inside the method A()
is actually the way to go.
Please show us the code that supposedly didn't work (there probably was another error in that code).
Solution 3
Its rather simple really, you have a series of mutator methods that all returns the original (or other) objects, that way 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 the function allows you to call the other function with the same object just like jQuery does.
Solution 4
I tried it and it worked
<?php
class C
{
public function a() { return $this; }
public function b(){ }
}
$c = new C();
$c->a()->b();
?>
Micah
Updated on July 09, 2022Comments
-
Micah almost 2 years
I am testing the way writing PHP like js, and I wonder if this will be possible.
If say I have A, B function in Class C.
Class C{ function A(){ } function B(){ } } $D = new C; $D->A()->B(); // <- Is this possible and how??
In Js, we can simple write
like D.A().B();
I tried
return $this
inside offunction A()
, didnt work.Thank you very much for your advice.
-
Micah over 11 yearsThank you very much!, and I found that I write something wrong...my bad to post the question..