Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically write a PHP object property name?

Tags:

php

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?

like image 403
user658182 Avatar asked Sep 24 '12 19:09

user658182


People also ask

Can we add dynamically named properties to JavaScript object?

In JavaScript, you can choose dynamic values or variable names and object names and choose to edit the variable name in the future without accessing the array. To do, so you can create a variable and assign it a particular value.

How Can Get object property value in PHP?

The get_object_vars() function is an inbuilt function in PHP that is used to get the properties of the given object.

What is PHP property?

Property is sometimes referred to as attribute or field. In PHP, a property is qualified by one of the access specifier keywords, public, private or protected. Name of property could be any valid label in PHP. Value of property can be different for each instance of class.


2 Answers

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.

like image 56
Jon Avatar answered Sep 29 '22 19:09

Jon


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]} 
like image 32
Mike Brant Avatar answered Sep 29 '22 19:09

Mike Brant