Serialize
It would be a lot more straightforward to use serialize and unserialize, which will handle the class initialization and type-checking for you.
E.g:
$person = new Person();
$person->firstname = 'Chuck';
$person->lastname = 'Jones';
$blob = serialize($person); // put blob in the database
Serialize / Unserialize Interface
If you want to follow the give_data()
approach (so your class properties match column names in the database, for example) you should specify an interface. An interface provides a guarantee that the class you're calling has the unserialize method available and that it behaves the way you expect (the example below uses a factory pattern):
<?php
interface ArraySerializable
{
public static function createFromArray($array);
}
class Person implements ArraySerializable
{
public static function createFromArray($array)
{
$temp = new self();
$temp->firstname = $array['first_name'];
$temp->lastname = $array['last_name'];
return $temp;
}
}
Then you'd test for class_implements()
$class_name = 'Person';
if (class_exists($class_name)
&& in_array('ArraySerializable', class_implements($class_name))
){
$person = $class_name::createFromArray(array(
'last_name' => 'Jones',
'first_name' => 'Chuck'
));
var_dump($person);
}
To use this with more classes you just implement the ArraySerializable
interface for each one.
If you don't want to roll this from scratch you can use a full-featured ORM like Doctrine to abstract the database away completely.