在PHP中声明类常量或属性时,只能为默认值指定原始值。因此,例如,该类声明将不起作用:
class TEST { const ABC = 2 * 4; const DEF = some_function(); static $GHI = array( 'key'=> 5 * 3, );}但是该类声明将:
class TEST { const ABC = 8; static $GHI = 15;}这些规则适用 于类常量/属性的默认值 -您始终可以使用表达式的结果初始化其他变量:
$a= array( 'a'=> 1 * 2, 'b'=> 2 * 2, 'c'=> 3 * 2,);
此类声明行为的原因如下:表达式就像动词。他们 做某事 。类就像名词:它们 声明某些东西
。声明性声明绝不应该产生动作声明的副作用。需要原始默认值将强制执行此规则。
考虑到这一点,我们可以如下重构原始类:
class SDK{ static protected $_types= null; static public function getType($type_name) { self::_init_types(); if (array_key_exists($type_name, self::$_types)) { return self::$_types[$type_name]; } else { throw new Exception("unknown type $type_name"); } } static protected function _init_types() { if (!is_array(self::$_types)) { self::$_types= array( 'STRING_NONE'=> 1 << 0, // ... rest of the "constants" here 'STRING_HOSTS'=> 1 << 6 ); } } function __construct($fString = null) { if (is_null($fString)) { $fString= self::getType('STRING_NONE') & self::getType('STRING_HOSTS'); } var_dump($fString); }}$SDK &= new SDK(SDK::getType('STRING_HOSTS'));


