PHP dynamic name for object property

2020-02-01 03:52发布

问题:

Instead of using

$object->my_property

I want to do something like this

$object->"my_".$variable

回答1:

Use curly brackets like so:

$object->{'my_' . $variable}


回答2:

How about this:

$object->{"my_$variable"};

I suppose this section of PHP documentation might be helpful. In short, one can write any arbitrary expression within curly braces; its result (a string) become a name of property to be addressed. For example:

$x = new StdClass();
$x->s1 = 'def';

echo $x->{'s' . print("abc\n")};
// prints
// abc
// def

... yet usually is far more readable to store the result of this expression into a temporary variable (which, btw, can be given a meaningful name). Like this:

$x = new StdClass();
$x->s1 = 'def';

$someWeirdPropertyName = 's' . print("abc\n"); // becomes 's1'.
echo $x->$someWeirdPropertyName;

As you see, this approach makes curly braces not necessary AND gives a reader at least some description of what composes the property name. )

P.S. print is used just to illustrate the potential complexity of variable name expression; while this kind of code is commonly used in certification tests, it's a big 'no-no' to use such things in production. )



标签: php oop