php - 从对象数组变量调用静态方法

标签 php arrays object static

在 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 - 从对象数组变量调用静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11519272/

相关文章:

java - 将 int[] 转换为 ArrayList

javascript - 奇怪的javascript对象问题

javascript - 将数组元素随机分配到新数组

c++ - 使用结构数组计算?

php - 在 Redis 中存储对象数组并检索它

php - mysql_num_rows 在第二个查询中返回 0

javascript - 使用复选框过滤到新的对象数组 - javascript

C++根据成员 bool 值对 vector 中的对象进行排序

php - 显示网页上的用户数量

php - PDO lastInsertId() 总是返回 0