I am new at PHP reflection so have an issue to create object from dump data.
class Car{
public $id;
public $name;
}
Car is my class. I can get class properties and values like this:
$audi = new Car();
$reflector = new ReflectionClass($audi);
var_dump($reflector->getDefaultProperties());
But I want to create instances of Car from array that comes from database.
$objects =array("id"=>"1", "name"=>"A3");
function createInstance($objects){
????
}
will be matched array key to class property.
As mentioned by Marc B, you can simply iterate the array to set the objects properties dynamically:
class Car{
public $id;
public $name;
}
function createInstanceOfCar($objects){
$car = new Car();
foreach ($objects as $key => $value)
$car->{$key} = $value;
return $car;
}
$objects =array("id"=>"1", "name"=>"A3");
$car1 = createInstanceOfCar($objects);
var_dump($car1);
It would probably be better however to have this functionality within the class its self, rather than an external function:
class CarAlternative{
public $id;
public $name;
function __construct(array $props){
foreach ($props as $key => $value)
$this->{$key} = $value;
}
}
$car2 = new CarAlternative($objects);
var_dump($car2);
One final note, php allows you to set undefined properties on an object, so if you where to modify the $objects
array to $objects =array("id"=>"1", "name"=>"A3", "wtf"=>"xxx");
then the above two objects would also contain a wtf
property.
To limit a class to defined properties, you can use the magic method __set
: http://php.net/manual/en/language.oop5.overloading.php#object.set
class CarStricter{
public $id;
public $name;
function __construct(array $props){
foreach ($props as $key => $value)
$this->{$key} = $value;
}
function __set($prop, $val){
//ignore undefined properties
}
}
The __set
method is called when an undefined property is set. As we do nothing in the method, we override the default behaviour
Live example: http://codepad.viper-7.com/XB86Qn
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.