Using OR operator when defining property in class
I am making an abstract class to ease up handling of properties.
Now I want to set some constant options to a property using the binary OR ( | ) operator.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开发者_Python百科 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;
}
This returns the following error:
Parse error: syntax error, unexpected '|'
How can I do this without having to type:
protected $_property__type = 17;
You could initialise the member's value in a constructor.
Yes, it's a bit minging. IMO the language should allow the expression here as the values are constants, but it does not. C++ fixes things like this in C++0x with constexpr
, but that doesn't help you here. :)
declare protected fields in __construct() or, if it is static class, use 'define' before class declaration:
define('myClass_property_type', VarType::STRING | VarType::READ_ONLY);
class myClass {
protected $_property = 'A string of text';
protected $_property__type = myClass_property_type;
}
But it's "dirty" method, don't use it for non-static class and try to avoid using it for any class.
It's not possible to declare it like that.
You can use your constructor to initialize the property.
Instead of what you're doing, try
(for static members, that is scoped to the class, shared across all instances)
class myClass {
protected static $_property;
protected static $_property__type;
}
myClass::$_property = 'A string of text';
myClass::$_property__type = VarType::STRING | VarType::READ_ONLY;
(for normal, non-static member variables)
class myClass {
function __construct()
{
$this->_property = "A string of text";
$this->_property__type = VarType::STRING | VarType::READ_ONLY;
}
...
}
精彩评论