我想有一个类属性,允许表达式发生在等号的右侧.所有版本的PHP都会阻塞以下代码,但它是以这种方式编写的,以便将来更容易扩展.
/* Example SDK Class */
class SDK
{
/* Runtime Option Flags */
// Strings
# 0: Makes no change to the strings.
var $STRING_NONE = (1 << 0);
# 1: Removes color codes from the string.
var $STRING_STRIP_COLOR = (1 << 1);
# 2: Removes language codes from the string.
var $STRING_STRIP_LANG = (1 << 2);
# 3: Removes all formatting from the string.
var $STRING_STRIP = SELF::STRING_STRIP_COLOR & SELF::STRING_STRIP_LANG;
# 4: Converts color codes to HTML & UTF-8.
var $STRING_HTML = (1 << 3);
# 8: Converts color codes to ECMA-48 escape color codes & UTF-8.
var $STRING_CONSOLE = (1 << 4);
# 16: Changes player names only.
var $STRING_NAMES = (1 << 5);
# 32: Changes host names only.
var $STRING_HOSTS = (1 << 6);
function SDK($fString = SELF::STRING_HTML & SELF::STRING_NAMES & SELF_HOST)
{
// constructor code.
}
}
$SDK &= new SDK(SDK::STRING_NONE);
(1<< 0)对我来说似乎是非常基本的语法,并且不能解释为什么PHP不允许这样的事情.任何人都可以想到一个可以保持以下代码的可读性和未来可扩展性的解决方案吗?
解决方法:
在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'));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。