2

When developing a PHP backend I've decided to use a static variable to save the logged in user. If I'm not mistaken this can only work if each call to the backend creates a new instance of that backend. Else when two calls overlap the logged in user might be overridden, producing a wrong result.

It's proving difficult to find the answer and so I tried writing a unit test that just checks if the static 'logged in user' variable still exists when a call to the backend is finished. This showed me that the variable was indeed null. Just to be sure I decided to ask this question here.

M0CH1R0N
  • 756
  • 9
  • 19

1 Answers1

2

Yes, and no. It does "create a new instance", in the sense that the static variable is not persisted between the two, and it does not, because it's not actually an "instance" per se, as intended in OOP context.

The static keyword refers to a static variable for that precise script run.

PHP will forget everything as soon as the response is sent. Each time PHP receives a request, the environment is recreated, nothing is persisted between two runs.


Using static for a user seems like a bad idea however. This is way too broad, but you should look into dependency injection, and mvc principles.