簡體   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