Well, you could cast it to stdClass:
$a = ['a' => 1, 'b' => 2];
$object = (object) $a;
But I guess you're not looking for that, you're probably trying to hydrate it.
In that case you could do something like this (assuming you're using public properties):
function castToObject(array $array, $className)
{
$object = new $className();
foreach ($array as $key => $val) {
$object->$key = $val;
}
return $object;
}
Or if you're using get-set methods, change assignment line to:
$setter = 'set' . ucfirst($key);
$object->$setter($val);
Final implementation may vary. You have 3 options I can think about:
- Make all your model classes extend some base class which implements this functionality.
- Create a trait that implements it
- Create a wrapper around your connection that does this (I suggest this)
Trait would look something like this:
trait FromArrayTrait
{
public static function fromArray(array $array)
{
$myClass = get_class();
$object = new $myClass();
foreach ($array as $key => $val) {
$object->$key = $val;
}
return $object;
}
}
And in each model you could just:
class MyModel
{
use FromArrayTrait;
public $a;
public $b;
}
And then in your logic:
$myArray = ['a' => 5, 'b' => 10];
$myModel = MyModel::fromArray($myArray);