PHP sets object properties dynamically

I have a function that needs to read an array and dynamically set the properties of an object.

class A { public $a; public $b; function set($array){ foreach ($array as $key => $value){ if ( property_exists ( $this , $key ) ){ $this->{$key} = $value; } } } } $a = new A(); $val = Array( "a" => "this should be set to property", "b" => "and this also"); $a->set($val); 

Well, obviously this does not work, is there any way to do this?

EDIT

It seems that there is nothing wrong with this code, the question should be closed

+8
object php setter
source share
2 answers

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

You can use 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) 
+8
source share

You only need to remove the brackets {} and work! → $this->$key = $value;

+20
source share

All Articles