php use语法无法识别,php – 未解析基本语法的解决方法

博客讨论了在PHP中如何处理类属性与表达式的问题,指出PHP不允许在声明类属性时使用等号右侧的表达式。文章提出了一个重构的解决方案,通过静态方法初始化和获取类型值来保持代码的可读性和可扩展性。在类的构造函数中,使用静态方法获取默认值,从而避免了直接在属性声明中使用复杂表达式。
摘要由CSDN通过智能技术生成

我想有一个类属性,允许表达式发生在等号的右侧.所有版本的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'));

标签:php,variables,class,arguments,bit-manipulation

来源: https://codeday.me/bug/20190916/1807895.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值