dongnong3799 2012-04-13 15:33
浏览 50
已采纳

调用常量会产生难以理解的解析错误

i am blocked by an incomprehensible syntax error that makes me crazy :/

The error displayed is Parse error: syntax error, unexpected '.', expecting ',' or ';'

This is the code that makes that:

class FamillePieceControllerCore extends FrontController
{
    public $php_self = 'famille-piece.php';

    private $webservice_url = _CICERONE_CONNECT_BASE_URL_ . 'WSC003&P2=0';
}

Where _CICERONE_CONNECT_BASE_URL_ is defined in a other file.

If i delete . 'WSC003&P2=0' the code works fine.

I don't understand :/ Thanks for helping

ps: I use php 5.3.8

  • 写回答

1条回答 默认 最新

  • duanjuelian4640 2012-04-13 15:35
    关注

    You cannot initialize a class property with an expression (like concatenation). Instead you must do it in the constructor:

    class FamillePieceControllerCore extends FrontController
    {
        public $php_self = 'famille-piece.php';
    
        private $webservice_url;
        public function __construct() {
          $this->webservice_url = _CICERONE_CONNECT_BASE_URL_ . 'WSC003&P2=0';
        }
    }
    

    From the documentation:

    Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. 

    This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

    Constants defined with define() are defined at runtime, so the value of _CICERONE_CONNECT_BASE_URL_ isn't known at compile time when the property is initialized.

    Update for later PHP versions:

    Beginning with PHP 5.6, simple expressions are permitted in class property declarations as long as they can still be evaluated at compile time. So the original posted code would compile and execute correctly in PHP 5.6+. Anything requiring runtime evaluation, such as a function call or variable interpolation is still not permitted.

    // This is okay in PHP 5.6+
    public $property = SOME_CONST . " other stuff";
    
    // This is still not possible since
    public $property = strlen(SOME_CONST);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。