簡體   English   中英

從對象數組變量調用靜態方法

[英]Calling static method from object array variable

在PHP中,您可以從對象實例(包含在數組中)中調用類的靜態方法,如下所示:

$myArray['instanceOfMyClass']::staticMethod(); // works

但由於某種原因,當我使用$this變量時,我得到一個解析錯誤。 例如:

$this->myArray['instanceOfMyClass']::staticMethod(); // PARSING ERROR

只是為了說明我的意思:

class MyClass{
    public static function staticMethod(){ echo "staticMethod called\n"; }
}

$myArray = array();
$myArray['instanceOfMyClass'] = new MyClass;
$myArray['instanceOfMyClass']::staticMethod(); // works

class RunCode
{
    private $myArray;

    public function __construct(){
        $this->myArray = array();
        $this->myArray['instanceOfMyClass'] = new MyClass;
        $this->myArray['instanceOfMyClass']::staticMethod(); // PARSING ERROR
    }
}

new RunCode;

關於如何解決這個問題的任何想法?

你實際上可以使用“ - >”來調用靜態方法:

$this->myArray['instanceOfMyClass']->staticMethod();

這是一個非常有趣的問題,它甚至可能是PHP本身的一個錯誤。

對於解決方法,請使用KISS原則。

class RunCode
{
    private $myArray;

    public function __construct(){
        $this->myArray = array();
        $this->myArray['instanceOfMyClass'] = new MyClass;

        $instance = $this->myArray['instanceOfMyClass']
        $instance::staticMethod();
    }
}

希望這可以幫助!

您將不得不使用臨時變量分解一個班輪,例如

$inst = $this->myArray['instanceOfMyClass'];
$inst::staticMethod()

這是PHP的編譯器不夠聰明,無法理解嵌套表達式的許多情況之一。 PHP開發人員最近一直在改進,但仍有工作要做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM