1

I have a class like:

class MyClass
{
    public static $myVariable;
}

... and inside I have this:

public static function set($name, $value)
{
    if (true === property_exists('MyClass', $name)) {
        self::$name = $value;
    }
}

How can I replace:

self::$name

... with the real variable name? I have try:

self::{$name}

... but it works only for methods. I want to have the possibility of change MyClass's variables with a function. For example:

MyClass::set('myVariable', 123);

Some ideas?

2
  • Does self::$name not work? Commented Dec 10, 2013 at 18:57
  • No, it search $name as class variable. Commented Dec 10, 2013 at 19:02

1 Answer 1

3

self::$$name should do the trick.

Sign up to request clarification or add additional context in comments.

1 Comment

"As opposed with isset(), property_exists() returns TRUE even if the property has the value NULL." Yup, static::${$name} looks better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.