Question

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?

Was it helpful?

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.

OTHER TIPS

You should write your code like this

$y->{X::foo} = 23;

Hope it helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top