在preg_replace中使用/e标志时,PHP不会评估只读属性
我想我们有这样的剧本:在preg_replace中使用/e标志时,PHP不会评估只读属性,php,preg-replace,Php,Preg Replace,我想我们有这样的剧本: class String { protected $text = null; public function __construct($text){ $this->text = $text; } public function __get($var){ return $this->$var; } public function replace($search, $replace, $limit = -1, $ignoreCase = false){
class String {
protected $text = null;
public function __construct($text){
$this->text = $text;
}
public function __get($var){ return $this->$var; }
public function replace($search, $replace, $limit = -1, $ignoreCase = false){
extract($GLOBALS, EXTR_REFS);
return preg_replace($search, $replace, $this->text, $limit, $count);
}
}
class Setting {
private $active = "not active";
public function __get($var){
return $this->$var;
}
}
$s = new Setting;
function replace(){
$string = new String('System is [var:$s->active]');
echo $string->replace('/\[var:([^\]]+)\]/ie', 'isset(\1)? \1: "";');
}
replace();
现在,$active
属性将不会计算
是虫子还是我应该做点特别的事
已解决非常感谢亲爱的Artefactor。
问题解决了
我应该实现
\uu isset
以使用只读属性的isset
函数您可能正在将常量
与私有
混合使用?!没有bug,如果您希望活动变量的行为类似于只读变量,则应将其声明为常量。像这样:
class Setting {
const ACTIVE = true;
public function __get($var){
return $var;
}
}
然后像这样访问它设置::ACTIVE
更新
它不会计算,因为您将变量括在单引号内。试试这个:
preg_replace('/(\{%active%\})/e', "$Setting->active", 'System is {%active%}');
缺少
/e
修饰符,不需要双引号或大括号。:) 您的\u get
定义错误。相反,您希望:
public function __get($var){
return $this->$var;
}
现在,所有属性都可以读取,但不一定要写入。您将无法读取在超类中定义的私有变量
例如:
<?php
class Setting {
private $active = "not active";
public function __get($var){
return $this->$var;
}
}
$s = new Setting;
echo preg_replace('/(\{%active%\})/e', '$s->active', 'System is {%active%}');
要使用isset()
我明白你的意思,但只读属性与类常量并不完全相同。@Shef:asBoltClock
说只读属性有些不同。只读属性在运行时可以是初始属性time@BoltClock当前位置它的行为会像一个,不是吗?我知道\uuu set()
和\uu get()
,但这比这要慢得多。然而,我不知道他到底想实现什么,也就是说,他正试图将类只读属性应用于哪个用例。它们在语义上是不同的,所以不能只说\u set()
和\u get()
更慢。类常量在编译时定义并与类关联;虽然只读属性可以与对象关联,并且往往可以在构造函数中私自设置(即只读适用于外部源)。@Omid Amraei:您在代码中的何处启动变量?如果你想完成另一件事,我想给你一个建议。基本上告诉你考虑一下这是否能解决你的问题。但是,我发现您想要的是真正的只读属性,而这已经是了。@Omid一旦您解决了这个问题,我看不出有什么问题。@Artefactor:您是对的,问题似乎是我的application@Artefacto例如我发现了问题。“当它不在全局范围内时它就不工作了,”我编辑道question@Omid如果要使用isset
,必须实现\uu isset
。
class Setting {
public function __isset($var){
return isset($this->$var);
}
}