0

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?

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Last question: There is no selfreplace function to do same solution?
@Ondra There is no selfreplace function in php. That is correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.