Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在类中定义属性时使用OR运算符_Php_Class_Php 5.3 - Fatal编程技术网

Php 在类中定义属性时使用OR运算符

Php 在类中定义属性时使用OR运算符,php,class,php-5.3,Php,Class,Php 5.3,我正在创建一个抽象类来简化属性的处理。 现在,我想使用二进制或(|)运算符为属性设置一些常量选项 class VarType { // Variable types const MIXED = 0; const STRING = 1; const INT = 2; const FLOAT = 3; const BOOL = 4; const ARRAY_VA

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

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;

这样申报是不可能的


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

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


是的,有点奇怪。在我看来,语言应该允许这里的表达式,因为值是常量,但它不允许。C++在C++ 0x中用“代码> CONTXPRPR <代码>修复了这类事情,但是这对你没有帮助。”p> 在_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;
}

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

请尝试使用它,而不是您正在执行的操作

(对于静态成员,其作用域为类,跨所有实例共享)

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


@Shakti:根本原因和解决方案是相同的,但这绝不是一个重复的问题。@Shakti:不,在我的例子中是关于使用常量的。在json的例子中,使用了一个方法。@ANisus:实际上是这样的。您的
|
操作是表达式的一部分,就像相关问题中的函数调用一样。但是我同意;这些相似之处不足以证明这是一个“复制品”。
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;
     }

 ...
 }