问题
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