Reputation: 57
I'am using memcache to store PHP class object using serialize and unserialize. Is any way to get back original class object using new Method?
My example:
class Test
{
public $id;
public function __construct($id)
{
if (InCache($id)) {
return unserialize(GetFromCache($id));
} else {
$this->id = $id;
SaveToCache(serialize($this));
}
}
}
Calling:
$t = new Test(1);
If ID is in cache or NOT, I need back same output:
Test Object
(
[id] => 1
)
Anybody can help?
Upvotes: 0
Views: 247
Reputation: 601
in php you can't return
in a __construct
function
you could get the new Object from a Factory Funktion like this:
class Test
{
public $id;
protected function __construct($id)
{
$this->id = $id;
SaveToCache(serialize($this));
}
public static function getNewObject($id)
{
if (InCache($id)) {
return unserialize(GetFromCache($id));
} else {
return new self($id);
}
}
}
Calling:
$t = Test::getNewObject(1);
Upvotes: 3