My solution that let you serialize inherited objects.
Without specify what need to be serialized.
We want to get rid of PDO object in this example.
abstract class DefaultModel() implements \Serializable
{
/**
* @var PDO
*/
private $pdo;
/**
* Serialize object
*
* @return string
*/
public function serialize()
{
$serializable = get_object_vars($this);
// unset property name that hold PDO instance
unset($serializable['pdo']);
return serialize($serializable);
}
/**
* Unserialize object
*
* @param string $serialized Serialized object
* @return DefaultModel
*/
public function unserialize($serialized)
{
$unserialized = unserialize($serialized);
// recreate PDO object
$this->pdo = $this->createDBObject();
if(is_array($unserialized) === true) {
foreach($unserialized as $property => $value) {
$this->{$property} = $value;
}
}
}
}
class RealModel extends DefaultModel
{
private $myVar;
public function setMyVar($value)
{
$this->myVar = $value;
}
}
$model = new RealModel();
$model->setMyVar('123456');
$serialized = serialize($model);
$serialized = $model->serialize(); // will also work
print_r($serialized);
$unserialized = unserialize($serialized);
print_r($unserialized);
Hope this help.