views:

36

answers:

2
$class = new Class;
$foo = json_decode($_POST['array']);

In this highly contrived example, I have a 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.

+1  A: 

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 );
}
ircmaxell
Cheers - that did it. Thanks for your help!
Julian H. Lam
+1  A: 

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);
Daniel Vandersluis
Oh yes, of course... foreach does $key => value as well... Cheers!
Julian H. Lam
Well, if you don't declare them, they will be public... Oh, and directly iterating over objects is not a great idea since they can implement the [`traversable`](http://us2.php.net/manual/en/class.traversable.php) interface (at which point the code won't work as expected). The cast (which you do in the code) is safe...
ircmaxell
@ircmaxell true they will be public, but this is pretty unavoidable unless the JSON object will always contain the same keys, in which case they can be pre-declared. And fair point about `traversable`, I wasn't aware of it.
Daniel Vandersluis