How to create my own object properly out of stdClass object

108 Views Asked by At

I'm creating instance of person according to data that i get from API response.

The data returns as \stdClass and i want to convert it to my own object. Is there a way to pass all the calls in the constructor and make something more elegant?

Class Person 
{
   protected $Name;
   protected $Email;
   ...
   protected $Property40;

   **// Is there an elegant way to do it? Assuming I know all the  property names**
   public function __construct(\stdClass $person) 
   {
      $this->Name       = $person->Name;
      $this->EMail      = $person->EMail;
      ...
      $this->Property40 = $person->Property40
   }

}

Tnx

1

There are 1 best solutions below

2
On BEST ANSWER
public function __construct(\stdClass $person) 
{
    foreach ($person as $attr => $val) {
       $this->$attr = $val;
    }
}