Julian H. Lam
Julian H. Lam

Reputation: 26124

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 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.

Upvotes: 2

Views: 912

Answers (2)

Daniel Vandersluis
Daniel Vandersluis

Reputation: 94153

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);

Upvotes: 1

ircmaxell
ircmaxell

Reputation: 165201

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 );
}

Upvotes: 2

Related Questions