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?

Était-ce utile?

La 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.

Autres conseils

You should write your code like this

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

Hope it helps

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top