使用变量类名和静态方法时出错

时间:2015-03-19 17:45:52

标签: php

运行PHP 5.4,所以我没有预料到这一点,但我遇到了以下错误:

Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)

假设您有一个stdClass设置变量,如下所示:

$this->variable = new stdClass();

$this->variable->other = array('class' => 'helloworld');

现在,假设您要访问类helloworld的静态方法:

// Standard call
$x = helloworld::my_static_method();

// Call with variable class name
$x = $this->variable->other['class']::my_static_method();

使用变量类名调用上面的内容时,我收到解析错误。奇怪的是,如果我执行以下操作,则不会出现错误:

$class = $this->variable->other['class'];

$x = $class::my_static_method();

对我来说,这看起来很奇怪,有人可以想到为什么在使用第一个例子和第二个例子时,类名没有正确解析的原因吗?

2 个答案:

答案 0 :(得分:1)

这不起作用($this->variable->other['class']::my_static_method()),因为它本质上直接使用字符串作为类名。它首先将它分配给变量时会起作用,因为它会被评估为类名。

您还可以考虑使用ReflectionMethod调用来调用该方法,在这种情况下,您不必在使用它之前将类名存储在变量中。以下是关于该文档的文档:http://php.net/manual/en/class.reflectionmethod.phpinvoke方法(您传入NULL以表示静态方法)http://php.net/manual/en/reflectionmethod.invoke.php

以下是一些调用函数的方法示例:

class helloworld{
    public static function my_static_method($i = 0){
        echo "Here: ".$i;
    }
}

class Foo{
    private $variable;

    public function __construct(){
        //Create a new class
        $this->variable = new stdClass();

        //Create a new property of the class, storing an array
        $this->variable->other = array('class' => 'helloworld');

        //Call function statically
        $x = helloworld::my_static_method(1); //Outputs: "Here: 1"

        //Store class name in a variable before use
        $class = $this->variable->other['class'];
        $y = $class::my_static_method(2); //Outputs: "Here: 2"

        //Using a ReflectionMethod, you can call the function this way, too
        $z = new ReflectionMethod($this->variable->other['class'], 'my_static_method');
        $z->invoke(null, 3); //Outputs: "Here: 3"
    }
}

//Instantiate new Foo class
new Foo();

答案 1 :(得分:1)

  

在使用第一个例子和第二个例子时,有没有人能想到为什么类名没有正确解析?

PHP解析器不支持这样的语法,而这仅仅是全部。这是因为解析器在历史上已经发展。我无法给出更多理由。

使用PHP 7,您可以看到这些语法详细信息的一些更改,更加符合您的预期方向Uniform Variable Syntax

($variable->other['class'])::my_static_method();

但在此之前,您可以在call_user_func

的帮助下解决这个问题
call_user_func([$variable->other['class'], 'my_static_method']);
call_user_func($variable->other['class'] . '::my_static_method');

或者当您自己编写时,通过创建变量:

$class = $variable->other['class'];
$class::my_static_method();

甚至是看起来不同的变量:

${(int)!${0}=$variable->other['class']}::my_static_method();

相关材料:

相关问题