How to access dynamic property by using variable?

半腔热情 提交于 2019-12-11 03:42:59

问题


See:

$class_members = get_class_vars(__CLASS__);

foreach($class_members as $key => $value)
{
    if (strpos($key, '_output') === 0)
    {
        // I want to eval() this
        $code = '$this->' . $key . ' = 0;';
    }
}

Assume I want to assign the value 0 to all class members that begin with _output. I plan to use eval. Good or bad idea?


回答1:


You don't need eval() for this. You can use a variable as in $this->{$key}:

foreach($class_members as $key => $value)
{
    if (strpos($key, '_output') === 0)
    {
        // Look mom, no eval()!
       $this->{$key} = 0;
    }
}



回答2:


You can just do:

$this->{$key} = 0;

There are only a few situations where eval isn't considered evil.

And this isn't one of them :)



来源:https://stackoverflow.com/questions/8137552/how-to-access-dynamic-property-by-using-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!