Take the 2-minute tour ×

I want to make a certain object 'static' between different runs of the php script, in order to optimize the performance of my scripts and avoid the initialization hit which is heavy. Is there a way to do this ?

share|improve this question
Why not to use cache ? ACP could be useful. –  joksnet Dec 17 '10 at 15:45
ACP ???? Help me. –  millebii Dec 17 '10 at 15:48
encrypted.google.com/search?hl=en&q=php+apc first hit (or third for wikipedia). –  Felix Kling Dec 17 '10 at 15:50
@joksnet: I think you mean APC... –  Felix Kling Dec 17 '10 at 15:51
Yes! Sorry: APC! –  joksnet Dec 17 '10 at 16:02
add comment

4 Answers

up vote 2 down vote accepted

You can put it into the user's session. Make sure, though, that the class is declared before session_start():

require 'heavy_class.php';

$_SESSION['heavy'] = new HeavyClass;
share|improve this answer
looking nice. I will try this method and answer back when I see the impact. –  millebii Dec 17 '10 at 16:29
Works fine, however it is actually slightly worse, looks like my init time is lower than serialize / deserialize approach. –  millebii Dec 18 '10 at 18:55
add comment

You can serialize the object and then persist it to either a local file or a database. This is best done using the php function serialize()

You then use unserialize() to restore the object.

There are some "gotchas" such that the object's class must be available to the executing script.

This will call the magic methods on the object being serialized __sleep() and __wakeup when it is serialized and unserialized respectively. Any database initialization should happen in these methods.

Link to the php docs: http://php.net/manual/en/function.serialize.php

share|improve this answer
+1 so I could address all the session solutions at once: Session will create LESS objects, but not a SINGLE object. If the goal is to have one single object, you need to do something else. Since session is user specific. –  DampeS8N Dec 17 '10 at 15:51
add comment

Serialize that object and store it in session :). In order to use it again user unserialize.

share|improve this answer
add comment

Stick it in a session, it will serialize it for you automatically. You can use the __wakeup and __sleep magic methods to handle any database connections and such, but you can avoid disk hits.

share|improve this answer
add comment

Your Answer


