Reputation: 1287
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 ?
Upvotes: 0
Views: 125
Reputation: 4711
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_start();
$_SESSION['heavy'] = new HeavyClass;
Upvotes: 2
Reputation: 8334
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.
Upvotes: 1
Reputation: 1357
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
Upvotes: 2
Reputation: 8446
Serialize that object and store it in session :). In order to use it again user unserialize.
Upvotes: 1