How do I dynamically write a PHP object property name?

php access object property with variable
php get variable name
php object array
php add to object
php var
php reference to object property
php object operator
php object initialization

I have object properties in my code that look like this:

$obj ->field_name_cars[0];
$obj ->field_name_clothes[0];

The problem is I have 100s of field names and need to write the property name dynamically. Otherwise, the object name and the keys for the property will always be the same. So I tried:

$obj -> $field[0];

Hoping that the name of the property would dynamically be changed and access the correct values. But, I keep getting 'undefined property $field in stdClass::$field;

More or less I am trying dynamically write the php before it executes so that it can output the proper values. Thoughts on how to approach this?

Update for PHP 7.0

PHP 7 introduced changes to how indirect variables and properties are handled at the parser level (see the corresponding RFC for more details). This brings actual behavior closer to expected, and means that in this case $obj->$field[0] will produce the expected result.

In cases where the (now improved) default behavior is undesired, curly braces can still be used to override it as shown below.

Original answer

Write the access like this:

$obj->{$field}[0]

This "enclose with braces" trick is useful in PHP whenever there is ambiguity due to variable variables.

Consider the initial code $obj->$field[0] -- does this mean "access the property whose name is given in $field[0]", or "access the element with key 0 of the property whose name is given in $field"? The braces allow you to be explicit.

Dynamically Access PHP Object Properties with $this, Instead, we need to dynamically calculate the property name, and then today in regards to the video Writing Custom Field Handlers Continued. In Object Oriented PHP, $this is a special "pseudo" variable inside the scope  Sometimes we need to be able to retrieve the value of a property on an object, but we don't know the name of that property. Instead, we need to dynamically calculate the property name, and then access the value.

I think you are looking for variable-variable type notation which, when accessing values from other arrays/objects, is best achieved using curly bracket syntax like this:

$obj->{field[0]}

Setting and Getting Property Values - Manual, Data object properties can be accessed using the object property access syntax. The following sets the company name to 'Acme'. <?php $company->name  How to create new property dynamically. If you want a dynamic property name like in this case we Browse other questions tagged php object properties or ask

The magic method __get is you friend:

class MyClass
{
   private $field = array();

   public function __get($name)
   {
      if(isset($this->field[$name]))
        return $this->field[$name];
      else
        throw new Exception("$name dow not exists");
   }
}

Usage:

$myobj = new MyClass();
echo $myobj->myprop;

Explanation: All your field data is stored in a array. As you access $myobj->myprop that property obviously does not exists in the class. That is where __get is called. __get looks up the name in the field array and returns the correct value.

Variable variables - Manual, The variable property name will be resolved within the scope from which the call You may think of using variable variables to dynamically generate variables from In this example, I needed to load an array with dynamically named objects​  Data object properties can be accessed via their property index using array syntax. The property index is the position at which the property's definition appears in the model (in this case the xml schema).

aboulfazl, since PHP 5.3.3 methods with the same name as the class won't be treated as constructor!

    YourClass
    {
        public $any = false;

        public function __construct($any = null)
        {
            $this->any = (is_null($any) ? $this->any : $any);
        }
    }

This works but wasn't ask by the topic owner, Jon gives the awnser!

How to dynamically access an object property?, This variable is casted to an object inside my model ($casts = []). I can read & write this without any problems while hardcoding thisbut is there a PHP-way to access this property using a variable? So I pass the name of the property of the binded class (i.e. $user) and wonna include the "checked"  Do not confuse php's version of properties with properties in other languages (C++ for example). In php, properties are the same as attributes, simple variables without functionality. They should be called attributes, not properties.

I worked on some code that used dynamically created object properties. I thought that using dynamically created object properties was pretty cool (true, in my opinion). However, my program took 7 seconds to run. I removed the dynamic object properties and replaced them object properties declared as part of each class (public in this case). CPU time went from over 7 seconds to 0.177 seconds. That's pretty substantial.

It is possible that I was doing something wrong in the way I was using dynamic object properties. It is also possible that my configuration is broken in some way. Of course, I should say that I have a very plain vanilla PHP configuration on my machine.

How to Dynamically Access Object Property Using Variable in , Where the dot notation is easier to read and write, the square bracket notation Therefore, if you've an object's property name stored in a JavaScript variable,  Further dereferencing a variable property that is an array has different semantics between PHP 5 and PHP 7. The PHP 7.0 migration guide includes further details on the types of expressions that have changed, and how to place curly braces to avoid ambiguity. Curly braces may also be used,

PHP Dynamic Object Accessibility Tutorial, PHP Dynamic Object With Array And Iterative Access Ability. Rana Ahsan May 29​, attribute definition: Lets write a simple class with few predefined attribute/​properties first: public function setName( $name ) {. $this ->name  Converting to object. If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. If the value was NULL, the new instance will be empty. An array converts to an object with properties named by keys and corresponding values. Note that in this case before PHP 7.2.0 numeric keys have been inaccessible unless iterated.

Dynamic Properties in PHP and StdClass · Kris Jordan, Looking at the official PHP documentation on objects and classes you Languages like JavaScript and Python allow object instances to have dynamic properties. So when does it make sense to use __get and __set ? You can add properties dynamically using some of the options below: In you example: var data = { 'PropertyA': 1, 'PropertyB': 2, 'PropertyC': 3 }; You can define a property with a dynamic value in the next two ways: data.key = value; or. data['key'] = value; Even more..if your key is also dynamic you can define using the Object class with:

Dynamic objects in JavaScript, An object can be defined as a list of properties, equivalent to the attributes of a class. You can add a property in accordance with the following syntax: objectname. Object is an instance of class B which is the child-class. This is particularly relevant with the dynamically-generated classes used by, for instance, database objects and the SoapClient class. Subject: using "sql_calc_found_rows" in a MySQL query while exploiting result in a PHP db class object.

Comments
  • This raw statement works in my code: echo $json_dump->geometry[6]->obs[2]->hayabusa2->delay_from; But I cannot "simulate" it by assigning "geometry[6]->obs[2]->hayabusa2->delay_from" to $path and using echo $json_dump->{$path} , i get "Undefined property: stdClass::$geometry[6] "
  • Don't do this. __get functions are performance hogs which you should avoid using when possible, on top of creating some serious issues with unexpected behaviour. This example is especially scary as it throws an exception which can cause serious app-breaking behaviour if the developer isn't planning on accessing a nonexistent attribute to throw an exception, turning a simple attribute access into a potential fatal error.