开发者

How long will an instance of a PHP class last?

How long does the instance of a class, object, in PHP last. Is it confined to the running script or will it last for a session? If it does last for a session is this regardless of whether the PHP script has start ed the session?

A simple question but this makes a big difference to me because it will mean user data will survive as an on the server and won't need storing in the session variable. Hence开发者_运维技巧 affecting some fundamentals of my design.

Thanks Colin


the question doesn't really belong to OOP but to PHP behavior in general

All PHP data is going nowhere as well as PHP script itself.

PHP scripts execution is atomic. It's not like a desktop application constantly running in your browser, and not even a daemon with persistent connection to your desktop application. It's more like a command line utility - doing it's job and exits.

That's why using external storage, like file or database is required. But of course you can save only strings there, not instances of variables or anything of the kind. Strings only.


It depends on the way PHP is configured. If PHP is configured as CGI, instances would be lost on each invocation. PHP would be invoked for each http request.

If PHP is configured as a module, then there would be multiple processes handling PHP requests. So, the instance would survive in "that particular" process. But subsequent requests might be handled by a different process.

If you need class instance to survive, you will need to serialize it and store it in DB or file.

If this information is transient (or stored somewhere else) you can store (seralize) it in session. One such example is user's full name which might be required for each http request, so it can be read from DB once and then stored in session.

Example of storing class instances in session : http://www.talkphp.com/advanced-php-programming/3407-storing-class-instance-into-session.html


It's nicely explained here :

How long does an instance variable persist? In Rails? In Java? In PHP?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜