【问题标题】:Parse error while declaring const integer in class in php在 php 的类中声明 const 整数时解析错误
【发布时间】:2015-05-02 11:17:30
【问题描述】:

我正在编写一个用户类,其中有一些常量变量。

class users{
    const integer USER_ACTIVATED = 1;
    const integer USER_BLOCKED = 0;
    const integer USER_SUBSCRIBED = 1;
    const integer USER_UNSUBSCRIBED = 0;

    private $user_id, $user_name, $user_password;

    public function __construct($user_id){
        $this->user_id = $user_id;
    }
}

这是一个缩小的测试用户类。当我尝试通过 localhost 运行此文件进行调试时,它给了我这个错误:

Parse error: syntax error, unexpected 'USER_ACTIVATED' (T_STRING), expecting '=' in C:\xampp\htdocs\test\Users.php on line 2 

我已经通过许多示例来解决问题,但一无所获。 任何帮助将不胜感激。

【问题讨论】:

  • integer 不是 php 中的关键字?!删除它
  • @Rizier123 我在 php 手册中找到了 const 整数声明,这就是我应用它的原因。无论如何我如何检查它是否工作正常?
  • 您在手册中哪里找到的?
  • 这可能无关紧要,但我在课堂上应用了反射方法,我在这里找到了它php.net/manual/en/class.reflectionmethod.php
  • @TeamIncredibles 也许是因为它是类定义?!您不要在类定义中放置 echo 语句!那是 PHP OOP 101,请阅读手册:php.net/manual/en/language.oop5.basic.php 您正在定义类,并且没有地方可以放置随机放置的 echo 语句。类定义中只有属性和方法定义

标签: php parsing integer constants


【解决方案1】:

就像Rizier123说的:integer在PHP中不是关键字。
因此 PHP 认为 integer 是变量的名称,因此需要等号而不是另一个标识符。

只需忽略integer,您就可以开始了:

class users
{
    const USER_ACTIVATED = 1;
    const USER_BLOCKED = 0;
    const USER_SUBSCRIBED = 1;
    const USER_UNSUBSCRIBED = 0;

    private $user_id, $user_name, $user_password;

    public function __construct($user_id)
    {
        $this->user_id = $user_id;
    }
}

【讨论】:

  • 我认为不仅对 OP 进行解释,而且对进一步的 SO 访问者也有帮助。
猜你喜欢
  • 1970-01-01
  • 2011-02-25
  • 1970-01-01
  • 2021-11-14
  • 1970-01-01
  • 2011-09-29
  • 1970-01-01
  • 2023-01-03
  • 1970-01-01
相关资源
最近更新 更多