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 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块
  • ¥15 nhanes加权logistic回归,svyglm函数