Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP dynamic name for object property

Tags:

oop

php

Instead of using

$object->my_property

I want to do something like this

$object->"my_".$variable
like image 426
Guesser Avatar asked Aug 23 '12 13:08

Guesser


People also ask

What is a dynamic property in PHP?

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.

How do you access the properties of an object in PHP?

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!

How do I declare an object in PHP?

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.


2 Answers

Use curly brackets like so:

$object->{'my_' . $variable}
like image 128
Madara's Ghost Avatar answered Sep 26 '22 08:09

Madara's Ghost


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

like image 34
raina77ow Avatar answered Sep 23 '22 08:09

raina77ow