Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access dynamic property by using variable?

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?

like image 398
StackOverflowNewbie Avatar asked Mar 18 '26 14:03

StackOverflowNewbie


2 Answers

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;
    }
}
like image 164
Michael Berkowski Avatar answered Mar 20 '26 08:03

Michael Berkowski


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 :)

like image 32
PeeHaa Avatar answered Mar 20 '26 09:03

PeeHaa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!