【问题标题】:PHP const not working?PHP 常量不起作用?
【发布时间】:2014-02-13 14:10:33
【问题描述】:

我的班级看起来像这样:

class Foo {
    const UNKNOWN = 2;

    public function doStuff($var) {
        if($var==UNKNOWN) {
            echo "Unknown state";
            return;
        }
        // other stuff
    }
}

但是,我在doStuff() 中收到此错误:

使用未定义的常量 UNKNOWN - 假定为 'UNKNOWN'

我做错了什么?我不能定义自定义常量吗?

【问题讨论】:

    标签: php class constants


    【解决方案1】:

    访问类中的常量时必须使用self:: 或类名:

    if($var == self::UNKNOWN) {
        echo "Unknown state";
        return;
    }
    

    【讨论】:

    • 仅供参考,提问者在我发布答案后更改了他们问题中的代码,这就是为什么我的答案与他们问题中的代码不匹配。
    • 是的,我更新它是正确的,对此感到抱歉。只需等待 13 分钟或任何需要的时间,我才能接受。
    • @JohnConde 好多了 ;)
    • @MightyPork 在常量是数组时变得更丑
    【解决方案2】:

    文档中有在 PHP 类中定义常量的例子。

    self:: will help 
    
    
      class Constants
    {
      //define('MIN_VALUE', '0.0');  WRONG - Works OUTSIDE of a class definition.
      //define('MAX_VALUE', '1.0');  WRONG - Works OUTSIDE of a class definition.
    
      const MIN_VALUE = 0.0;      // RIGHT - Works INSIDE of a class definition.
      const MAX_VALUE = 1.0;      // RIGHT - Works INSIDE of a class definition.
    
      public static function getMinValue()
      {
        return self::MIN_VALUE;
      }
    
      public static function getMaxValue()
      {
        return self::MAX_VALUE;
      }
    }
    

    【讨论】:

      【解决方案3】:

      要使用 php 中的每个动态字段,您必须调用 $this->field 并且要在 php 中使用每个静态字段和 const,您必须调用 self::field

      示例:

          class ApiController {
      
                public static $static= "";
                public $dynamic= "";
      
                public function __construct() {
                $a=$this->$dynamic;
                $b=self::$static;
          }
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-27
        • 2014-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-25
        • 2012-05-22
        • 2013-11-10
        相关资源
        最近更新 更多