PHP Dynamic Name for Object Property

How do I dynamically write a PHP object property name?

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.

PHP dynamic name for object property

Use curly brackets like so:

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

PHP: Dynamic Object Names

$query = $this->Queryparts->{$type}['filter'];

PHP - Accessing a object property from dynamic variable

I don't think you can make multiple dereferences this way. You'll be looking for a variable in $object called user->name. Instead, you can split by -> and then make multiple calls, something like:

$test = 'user->name';
$val = $object;
foreach(explode('->', $test) as $item) {
$val = $val->$item;
}
echo $val; # This is the result of $object->user->name

Sample Code

How do you access a dynamic property in an object?

This won't work in PHP < 7.2.0 and the issue is that the string-integer array keys are actually converted to integer property names, not strings. An alternate way to get an object from an array that will work:

$var = json_decode(json_encode(array('1' => 'Object one','2' => 'Object two')));
$num = "2";
var_dump( $var->$num );

See the Demo, in PHP < 7.2.0 the (object) cast converts to integer properties but json_decode creates string properties.

PHP set object properties dynamically

http://www.php.net/manual/en/reflectionproperty.setvalue.php

You can using Reflection, I think.

<?php 

function set(array $array) {
$refl = new ReflectionClass($this);

foreach ($array as $propertyToSet => $value) {
$property = $refl->getProperty($propertyToSet);

if ($property instanceof ReflectionProperty) {
$property->setValue($this, $value);
}
}
}

$a = new A();

$a->set(
array(
'a' => 'foo',
'b' => 'bar'
)
);

var_dump($a);

Outputs:

object(A)[1]
public 'a' => string 'foo' (length=3)
public 'b' => string 'bar' (length=3)

Insert dynamic Object property names into Database

You can set an array of key => variable names, then loop over those values to see if they exist in the $item variable and, if so, add that value to the data to be inserted into the db:

//default array of data to insert
$data = [
'platform' => $item['Platform'],
'qty' => $item['qty'],
'rate' => number_format($item['rate'], 2, '.', ''),
'rel_id' => $insert_id,
'rel_type' => 'estimate',
'item_order' => $item['order'],
'unit' => $item['unit']
];

//Get column names from db
$plat_options = $this->db->get('tblplatform_options')->row()->name;
// $plat_options = [RAM, HardDrive]

//Check if $item[$name] exists. If it does, add that to the
// array of data to be inserted
foreach($plat_options as $key) {
if(array_key_exists($key, $item)) {
$data[$key] = $item[$key];
}
}

$this->db->insert('tblitems_in', $data);

edit

I'm not sure this will work (I don't understand the use case).

It is possible, using array_diff_key to get a list of array keys that exist in $item but not in $data. With this array of keys, you can add the missing keys.

I have altered my previous code to demonstrate this.

PHP: how to resolve a dynamic property of an object that is multiple levels deep

PHP doesn't automatically resolve a string containing multiple path levels to children of an object like you are attempting to do.

This will not work even if $obj contains the child hierarchy you are expecting:

$obj = ...;  
$path = 'level1->level2->level3';
echo $obj->$path; // WRONG!

You would need to split up the path and "walk" through the object trying to resolve the final property.
Here is an example based on yours:

<?php
$obj = new stdClass();
$obj->name = 'Fred';
$obj->job = new stdClass();
$obj->job->position = 'Janitor';
$obj->job->years = 4;
print_r($obj);

echo 'Years in current job: '.string($obj, 'job->years').PHP_EOL;

function string($obj, $path_str)
{
$val = null;

$path = preg_split('/->/', $path_str);
$node = $obj;
while (($prop = array_shift($path)) !== null) {
if (!is_object($obj) || !property_exists($node, $prop)) {
$val = null;
break;

}
$val = $node->$prop;
// TODO: Insert any logic here for cleaning up $val

$node = $node->$prop;
}

return $val;
}

Here it is working: http://3v4l.org/9L4gc

how to do PHP object reference with an arrow pointer operator to a dynamically generated value

You have to use brackets for variable variables. You'll then be able to dynamically create your object:

$jobObject->{$keys[$i]} = $row[$i];

Take a look at the php documentation this subject: http://php.net/manual/en/language.variables.variable.php

isset() with dynamic property names

Try adding braces around the property name...

isset( $Object->{$tst}[ $one ] );

CodePad.



Related Topics



Leave a reply



Submit