简体   繁体   中英

How do I call a static method of a class stored as a variable?

Why, in a class instance context, don't calls of the form $this->className::staticMethod work, but calls of the form $className::staticMethod do work?

In the example below callDoSomething2 works, but callDoSomething does not work (I get a parser error). I'm using PHP version 5.3.15.

<?php
class A {
    private $className;

    public function __construct($className) {
        $this->className = $className;
    }

    public function callDoSomething() {
        $this->className::doSomething();
    }

    public function callDoSomething2() {
        $className = $this->className;
        $className::doSomething();
    }
}

class B {
    public static function doSomething() {
        echo "hello\n";
    }
}

$a = new A('B');
$a->doSomething();

callDoSomething2是一种实现方式,另一种方式是使用类似于

call_user_func("{$this->className}::doSomething");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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