map array to class object

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mcog_esteban
Forum Contributor
Posts: 127
Joined: Tue Dec 30, 2003 3:28 pm

map array to class object

Post 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]
User avatar
aaronhall
DevNet Resident
Posts: 1040
Joined: Tue Aug 13, 2002 5:10 pm
Location: Back in Phoenix, missing the microbrews
Contact:

Post by aaronhall »

User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: map array to class object

Post 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.
(#10850)
mcog_esteban
Forum Contributor
Posts: 127
Joined: Tue Dec 30, 2003 3:28 pm

Post by mcog_esteban »

Thank you both.
Post Reply