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 浏览文件夹的图库,视频,图片之类的怎样删除?
  • ¥15 怎么把512还原为520格式
  • ¥15 MATLAB的动态模态分解出现错误,以CFX非定常模拟结果为快照
  • ¥15 求高通平台Softsim调试经验
  • ¥15 canal如何实现将mysql多张表(月表)采集入库到目标表中(一张表)?
  • ¥15 wpf ScrollViewer实现冻结左侧宽度w范围内的视图
  • ¥15 栅极驱动低侧烧毁MOSFET
  • ¥30 写segy数据时出错3
  • ¥100 linux下qt运行QCefView demo报错
  • ¥50 F1C100S下的红外解码IR_RX驱动问题