donglan6967 2015-03-19 17:45
浏览 77
已采纳

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

Running PHP 5.4, so I wasn't expecting this, but I'm encountering the following error:

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

Assume you have a variable of stdClass setup as follows:

$this->variable = new stdClass();

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

Now, assume you want to access a static method of class helloworld:

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

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

When calling the above using the variable class name, I receive the parsing error. What's odd, is that if I do the following, no error is presented:

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

$x = $class::my_static_method();

To me this seems very odd, can anyone think of a reason why the class name isn't resolving correctly when using the first example versus the second?

  • 写回答

2条回答 默认 最新

  • duanmie9741 2015-03-20 10:24
    关注

    can anyone think of a reason why the class name isn't resolving correctly when using the first example versus the second?

    The PHP parser does not support such a syntax, and that's merely all. This is because the parser has grown historically. I can't give more reason than that.

    It will be that with PHP 7 you can see some changes on these syntax details working more into your expected direction Uniform Variable Syntax:

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

    But until then, you can go around that with the help of call_user_func:

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

    Or as you wrote your own, by creating a variable:

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

    Or even a variable that looks like something different:

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

    Related Material:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?