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 will create a new stdClass and doesn't help me much. Are there any easy one or two line methods to make each $key => $value
pair in my array into a $key = $value
variable for my class? I don't find it very logical to use a foreach loop for this, I'd be better off just converting it to a stdClass and storing that in a variable, wouldn't I?
class MyClass {
var $myvar; // I want variables like this, so they can be references as $this->myvar
function __construct($myarray) {
// a function to put my array into variables
}
}
Here's another solution using
PDOStatement::fetchObject
, though it is a bit of a hack.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.
If you want to cast nested array to object use this code:
Then you can use like this:
This simple code should work:
Example usage
Alternatively, this might be a better approach
Usage is the same
if you (like me) came here looking for a source code generator for array->class, i couldn't really find any, and then i came up with this (a work in progress, not well tested or anything, json_decode returns the array.):
output:
Best solution is to have trait with static function
fromArray
that can be used for data loading:Then you can use this trait like that:
Then you can call static
fromArray
function to get new instance of Example class:I also have much more sophisticated version with nesting and value filtering https://github.com/OzzyCzech/fromArray