开发者

PHP does not evaluate readonly properties when using /e flag in preg_replace

开发者 https://www.devze.com 2023-03-14 05:20 出处:网络
think we have this script : class String { protected $text = null; public function __construct($text){ $this->text = $text;

think we have this script :

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;
}
}

$开发者_如何学Pythons = new Setting;

function replace(){
$string = new String('System is [var:$s->active]');
echo $string->replace('/\[var:([^\]]+)\]/ie', 'isset(\1)? \1: "";');
}

replace();

now $active property will not evaluate is it a bug or i should do something special ?

SOLVED

with a lot of thanks to dear Artefacto.

the problem was solved

i should implement __isset to use isset function for readonly property


Your __get definition is wrong. You want instead:

public function __get($var){
    return $this->$var;
}

Now everything property can be read, but not necessarily written to. You just won't be able to read private variables defined in superclasses.

For instance:

<?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%}');

will print "System is not active".


You are mixing const with private, maybe?! There is no bug, if you want the variable active to behave like a readonly one, you should declare it as a constant. Like this:

class Setting {
    const ACTIVE = true;

    public function __get($var){
        return $var;
    }
}

Then access it like this Setting::ACTIVE.

Update

It won't evaluate because you are enclosing the variable inside single quotes. Try this:

preg_replace('/(\{%active%\})/e', "$Setting->active", 'System is {%active%}');

Missed the /e modifier, no need for double quotes or braces. :)


Have to implement __isset function for String class when want to use isset()

class Setting {
    public function __isset($var){
        return isset($this->$var);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号