PHP Object/Variable Life Time

Sharing is Caring

I’m hoping to use this post as a way of clarifying the lifetime of an object in PHP because I am continually running into webdesigners and programmers that don’t understand the lifetime.

To simplify, in PHP between requests only the variables in the contents of $_SESSION are retained. This means that whenever a script executes objects and variables are created and upon completion all objects/variables are destroyed. Many programmers that have programmed in more traditional object oriented languages like C# or Java often build extensive object hierarchies that will be rebuilt on every request unless stored in $_SESSION, cookies, or some other external store.

Unfortunately, many of the patterns and refactorings suggested by the Gang of Four have to be used with caution in PHP because of the stateless nature. The stateless nature of PHP does allow us a lot of extensibility though and allows for much greater scalability.

Sharing is Caring