Page 1 of 1

map array to class object

Posted: Thu Jan 18, 2007 12:22 pm
by mcog_esteban
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Hello.
I'm trying to map an array to a specific class, and i have done this:

Code: Select all

//Found on http://www.php.net

function typecast($old_object, $new_classname) 
{
  		if(class_exists($new_classname)) 
  		{
   			$old_serialized_object = serialize($old_object);
   			$new_serialized_object = 'O:' . strlen($new_classname) . ':"' . $new_classname . '":' .
            	substr($old_serialized_object, $old_serialized_object[2] + 7);
   		return unserialize($new_serialized_object);
  		}
  		else
   		return false;
}


//Mapping an array to a class Client
$row = array('name' => 'Some Name', 'adress' => 'Some Adress', 'phone' => 'Some Phone');
$std = new stdClass();
foreach($row as $key => $value)
{
     $std->$key = $value;
}

$cliente = typecast($std, "Client");
This seems to work fine, my question is:
Is there any way to do this more elegantly or more "professionallly" ?

Because despite sometimes things are working doesn't mean they are correct.
I hope i explained the subject ok.


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Thu Jan 18, 2007 12:25 pm
by aaronhall

Re: map array to class object

Posted: Thu Jan 18, 2007 12:42 pm
by Christopher
Maybe:

Code: Select all

class stdClass {

     function import ($row) {
          foreach($row as $key => $value) {
               $this->$key = $value;
          }
     }
}

class Client extends stdClass { ... }

$row = array('name' => 'Some Name', 'adress' => 'Some Adress', 'phone' => 'Some Phone');
$client = new Client();
$client->import($row);
You could do it in the constructor as well.

Posted: Thu Jan 18, 2007 3:11 pm
by mcog_esteban
Thank you both.