【问题标题】:__CLASS__ PHP. Need a clarification on this one.__CLASS__ PHP。需要对此进行澄清。
【发布时间】:2016-04-15 00:21:58
【问题描述】:
class foo {
  const bar1 = 10.0;
  const bar2 = 2.22;
  const bar3 = 5.12;

    function getTotal($some_string, $some_number) {
      $total = 0.0;
      // Why would this flag a warning? 
      // $what_is_const = constant("bar" . $some_string);            // DOES NOT WORK!
      $what_is_const = constant(__CLASS__ . "::bar" . $some_string); // WORKS!
      $total += $what_is_const * $some_number;  
    } 
}

警告:常量():找不到常量//具有完全相同的名称!

问题是:为什么要识别类名才能访问常量; 是范围问题还是其他问题?

【问题讨论】:

  • 是的,它是class constant
  • 是的,但为什么会这样呢?
  • 因为你已经这样声明了。
  • 这是否意味着如果它是一个类 const,为了访问 bar1 我必须明确声明 constant("foo::bar1");constant("bar1"); // that is if bar1!=const 相比?

标签: php constants


【解决方案1】:

...是范围界定问题还是其他问题?

你成功了!
当您定义了一个局部常量(在类内部)时,它是一个class constant

为了访问类常量,您应该在前面加上一个类名(当引用外部类时)或通过 self, static 关键字,如下所示:

class Foo {
   const BAR = 1;

   function getBar() { return self::BAR; }
}

【讨论】:

    【解决方案2】:

    如果你有一个类外的常量,它的行为就像一个类外的常量。如果你在一个类中声明一个常量,它几乎就像一个静态属性并且可以以非常相似的方式访问(例如,类内的self::MY_CONSTANT或类外的Foo::MY_CONSTANT;比较self::$staticPropertyFoo::$staticProperty) .

    这有助于确定哪些类被用作依赖项,以及常量的实际定义位置。这样,它通常允许常量更具可读性,因为它为常量相关的内容提供了上下文线索。

    顺便说一句,让常量完全大写并带有下划线是一种很好的风格(例如,MY_CONSTANT 而不是myConstant)。此外,类名通常被引用为大写驼峰式(MyClass 而不是myclass)。

    【讨论】:

    • 上下文线索,明白了!
    猜你喜欢
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多