Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a php Singleton class instance be retained across multiple sessions?

Tags:

php

For the sake of a simple example, if I want to count the number of hits a script gets without the use of disk storage, can I do this with a static class member?

User1:

<?php
$test = Example::singleton();
$test->visits++;
?>

User2:

<?php
$test = Example::singleton();
$test->visits++;
?>

Will the value of $visits be 1 or 2?

like image 837
Kevin Avatar asked Dec 11 '25 09:12

Kevin


2 Answers

No. Each request will spawn a new process. Nothing survives between them.

You can retain state using sessions, which are essentially a disk-based serialization mechanism. Sessions them selves rely on cookies to identify the data between requests (But the data it self is stored in a file on the server). As such, they are local to the user and not suitable for your needs. The standard way to store that kind of data in a PHP application would be in a database.

like image 104
troelskn Avatar answered Dec 12 '25 22:12

troelskn


$visits will be 1 in both case.

Singletons are per request and not per machine / host. Each request will have its own instance.

I don't think you can count the number of hits for one page without some kind of disk storage / database.

like image 22
krtek Avatar answered Dec 12 '25 21:12

krtek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!