【问题标题】:Using OR operator when defining property in class在类中定义属性时使用 OR 运算符
【发布时间】:2011-08-08 19:56:54
【问题描述】:

我正在创建一个抽象类来简化属性的处理。
现在我想使用二元 OR ( | ) 运算符为属性设置一些常量选项。

class VarType
{
    // Variable types
    const MIXED         = 0;
    const STRING        = 1;
    const INT           = 2;
    const FLOAT         = 3;
    const BOOL          = 4;
    const ARRAY_VAL     = 5;
    const OBJECT        = 6;
    const DATETIME      = 7;

    // Variable modes
    const READ_ONLY     = 16;
    const NOT_NULL      = 32;
}

class myClass {
    protected $_property = 'A string of text';
    protected $_property__type = VarType::STRING | VarType::READ_ONLY;
}

这会返回以下错误:

解析错误:语法错误,意外'|'

如何在不输入的情况下做到这一点:

protected $_property__type = 17;

【问题讨论】:

  • @Shakti:根本原因和解决方案是一样的,但这绝不是重复的问题。
  • @Shakti:不,就我而言,它是关于使用常量。在 json-case 中使用了一个方法。
  • @ANisus:实际上是这样。您的 | 操作是表达式的一部分,就像相关问题中的函数调用一样。但是我同意;相似之处不足以保证将其称为“重复”。

标签: php class php-5.3


【解决方案1】:

试试看

(对于静态成员,范围为类,在所有实例之间共享)

class myClass {
    protected static $_property;
    protected static $_property__type;
}

myClass::$_property = 'A string of text';
myClass::$_property__type = VarType::STRING | VarType::READ_ONLY;

(对于普通的非静态成员变量)

class  myClass {
     function __construct()
     { 
         $this->_property = "A string of text";
         $this->_property__type = VarType::STRING | VarType::READ_ONLY;
     }

 ...
 }

【讨论】:

    【解决方案2】:

    在 __construct() 中声明受保护的字段,或者,如果它是静态类,则在类声明之前使用'define':

    define('myClass_property_type', VarType::STRING | VarType::READ_ONLY);
    
    class myClass {
        protected $_property = 'A string of text';
        protected $_property__type = myClass_property_type;
    }
    

    但它是“肮脏”的方法,不要将其用于非静态类,并尽量避免将其用于任何类。

    【讨论】:

      【解决方案3】:

      您可以在构造函数中初始化成员的值。

      是的,它有点响。 IMO 语言应该允许此处的表达式,因为值是常量,但它不允许。 C++ 使用constexpr 在 C++0x 中修复了此类问题,但这对您没有帮助。 :)

      【讨论】:

        【解决方案4】:

        这样声明是不可能的。

        您可以使用您的构造函数来初始化属性。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-28
          • 2021-08-17
          • 2015-07-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多