Search code examples
phpclass-constants

PHP Object access with class constant


Is it possible in PHP to access a member of an object where the name of the member is specified by a class constant?

Consider this example:

class X{
    const foo = "abc";
}

class Y{
    public $abc;
}

$y = new Y();

$y->X::foo = 23; //This does not work

The parser doesn't accept the last line but this is what I want. I want to access the field with the name stored in the class constant X::foo. Is there a syntax to achieve that?


Solution

  • Use variable variables, either via a temp or directly:

    $name = X::foo;          // Via temp var
    $y->$name = 23;          // Access the member by the string's content
    var_dump($y->{X::foo});  // Dumps 23
    

    Working sample here.