I have this class:
class myClass
{
function A() {
$x = "Something ";
return $x;
}
function B() {
return "Strange";
}
}
But I want to call the function like this:
myClass()->A()->B();
How can i do that without return the class itself(return $this)?
In order to achieve method chaining, your methods from the chain (except the last one) must return an object (in many cases and also in yours $this
).
If you would want to build a string with method chaining, you should use a property to store it. Quick example:
class myClass
{
private $s = "";
function A() {
$this->s .= "Something ";
return $this;
}
function B() {
$this->s .= "Strange";
return $this;
}
function getS() {
return $this->s;
}
}
// How to use it:
new myClass()->A()->B()->getS();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.