How to convert array, passed into object constructor, to object's properties?
What s开发者_JAVA技巧hould I put into class to be able to do so?
$data = array(
'a' => 12345,
'b' => 67890,
);
$object = new Class($data);
echo $object->a; //outputs 12345
echo $object->b; //outputs 67890
Ignacio Vazquez-Abrams’s answer is nice, but I'd prefer a whitelist of attributes you would like to allow to be set this way:
foreach(array('attribute1', 'attribute2') as $attribute_name) {
if(array_key_exists($attribute_name, $data)) {
$this->$attribute_name = $data[$attribute_name];
}
}
This way you can make sure no private attributes are set.
Alternatively, if you're just after the object syntax, you can do:
$object = (object) $data;
$object = $data->a // = 12345
This is coercing the array into a StdClass
.
class A {
private $data;
public function __get($key) {
return isset($this -> data[$key]) ? $this -> data[$key] : false;
}
public function __construct(array $data) {
$this -> data = $data;
}
}
foreach($arr as $key => $val)
{
this->$key = $val;
};
class MyClass {
private $a;
private $b;
public function __construct(array $arr) {
$this->a = $arr['a'];
$this->b = $arr['b'];
}
}
Depending on your UseCase, this might be an alternative to the given solutions as well:
class A extends ArrayObject {}
This way, all properties in the array will be accessible by object notation and array notation, e.g.
$a = new A( array('foo' => 'bar'), 2 ); // the 2 enables object notation
echo $a->foo;
echo $a['foo'];
As you can see by the class declaration, ArrayObject implements a number of interfaces that allow you to use the class like an Array:
Class [ <internal:SPL> <iterateable> class ArrayObject
implements IteratorAggregate, Traversable, ArrayAccess, Countable ]
It also adds a number of methods to complete array access capabilities. Like said in the beginning, this might not be desirable in your UseCase, e.g. when you don't want the class to behave like an array.
精彩评论