繁体   English   中英

PHP-从类中的另一个函数调用后调用函数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM