Adding to a class' variables with elements in an object
$class = new Class;
$foo = json_decode($_POST['array']);
In this highly contrived example, I have a开发者_Python百科 class with its own functions and variables, blah blah.
I also just decoded a JSON string, so those values are now in$foo
. How do I move the elements in $foo
over to $class
, so that:
$foo->name
becomes $class->name
?
Would be trivial if I knew what all the elements were, yes... except for the sake of being dynamic, let's say I want them all transferred over, and I don't know their names.
You could use get_object_vars
:
$vars = get_object_vars($foo);
foreach ($vars as $key => $value) {
$class->$key = $value;
}
You could also implement this in your class:
public function bindArray(array $data) {
foreach ($data as $key => $value) {
$this->$key = $value;
}
}
And then cast the object into an array:
$obj->bindArray( (array) $foo );
or add a method to do that too:
public function bindObject($data) {
$this->bindArray( (array) $data );
}
Add a function to your class to load values from an object, and then use foreach
to iterate over the object's properties and add them to the class (you do not need to declare your class members before you initialize them):
class Class
{
function load_values($arr)
{
foreach ($arr as $key => $value)
{
$this->$key = $value;
}
}
}
$class = new Class;
$foo = json_decode($_POST['array']);
$class->load_values((array)$foo);
精彩评论