Instead of using
$object->my_property
I want to do something like this
$object->"my_".$variable
Dynamic properties are property that are not declared in the class, but in the code in your class, you want to use a not declared property: class User { public string $name; public function __construct($name="", $age = 0) { $this->name = $name; // Assigns the not existent property age.
The most practical approach is simply to cast the object you are interested in back into an array, which will allow you to access the properties: $a = array('123' => '123', '123foo' => '123foo'); $o = (object)$a; $a = (array)$o; echo $o->{'123'}; // error!
To create an Object in PHP, use the new operator to instantiate a class. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created.
Use curly brackets like so:
$object->{'my_' . $variable}
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. )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With