[英]PHP - Call function from after call to another function in the class
我有这个课:
class myClass
{
function A() {
$x = "Something ";
return $x;
}
function B() {
return "Strange";
}
}
但是我想这样调用函数:
myClass()->A()->B();
我该如何做而不返回类本身(返回$ this)?
为了实现方法链接,链接中的方法(最后一个除外)必须返回一个对象(在许多情况下以及在您的$this
)。
如果要使用方法链接构建字符串,则应使用属性来存储它。 快速示例:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.