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}
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 - 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
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.
How to create new property dynamically
There are two methods to doing it.
One, you can directly create property dynamically from outside the class:
class Foo{
}
$foo = new Foo();
$foo->hello = 'Something';
Or if you wish to create property through your createProperty
method:
class Foo{
public function createProperty($name, $value){
$this->{$name} = $value;
}
}
$foo = new Foo();
$foo->createProperty('hello', 'something');
php dynamically created class object has two properties with the same name cant figure out why
Fixed it by just making a new csv file and manually typing the csv headings.
The original file was saved via excel.
My guess is some sort of text encoding was causing the issue.
Editing the the original file by deleting the headings and typing them again wasn't working but creating a new file and typing it out fixed the issue.
Al-tho I have resolved the issue I'd still love to hear anyone's ideas on why this happened and how to make the some generic code to ignore any weird text encoding in the csv file.
I think possible this might have been a better answer if I was in the situation where recreating the source file wasnt an option.
Remove non-utf8 characters from string
PHP: Dynamic Object Names
$query = $this->Queryparts->{$type}['filter'];
Related Topics
Prevent Innodb Auto Increment on Duplicate Key
PHP Send E-Mail with Attachment
Automatic Image Format Detection in PHP
How to Use Objects from Other Namespaces and How to Import Namespaces in PHP
How to Add Text to an Image with PHP Gd Library
Ajax File Download Using Jquery, PHP
How to Catch This Error: "Notice: Undefined Offset: 0"
My Magento Extension Install Script Will Not Run
Accept Function as Parameter in PHP
Binding Parameters for Where in Clause with Pdo
Cloudflare and Logging Visitor Ip Addresses via in PHP
Custom Pagination View in Laravel 5
Reconstruct/Get Source Code of a PHP Function
Iterate Over Each Line in a String in PHP
Php: Check If a File Is Loaded Directly Instead of Including