简体   繁体   中英

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?

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 .

You should write your code like this

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

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM