Simple question, how do I convert an associative array to variables in a class? I know there is casting to do an (object) $myarray
or whatever it is, but that w
Define a static method to convert get an instance from an array. Best, define an interface for it. This is declarative, does not pollute the constructor, allows you to set private properties and still implement custom logic that would not be possible with Reflection. If you want a generic solution, define a trait and use it in your classes.
class Test implements ContructableFromArray {
private $property;
public static function fromArray(array $array) {
$instance = new self();
$instance->property = $array['property'];
return $instance;
}
}
interface ConstructableFromArray {
public static function fromArray(array $array);
}