0

I know this has already been discussed multiple times here but I would like to further and clear understanding why it's bad practice to use global variables. Does it becomes dangerous on the concurrent http requests? if this is the code:

<?php
    $variable1 = $_REQUEST['userinput'];
    sleep(3000);
    echo $variable1;
?>

if there are users like user1, user2.. if user1's input is 'request1' and user2's input is 'request2' that is passed to $_REQUEST['userinput'] variable, then concurrent sending of requests happens, will the echoed $variable1 be displayed as what the respective users have input to their browser or it will override the first user's input by the last user's input? apologies for my poorly written post and for this repeated inquiry. I just like to have clear understanding about global variables.

aj go
  • 453
  • 1
  • 7
  • 20
  • https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil – Iłya Bursov Jan 06 '18 at 06:12
  • 1
    Possible duplicate of [Are global variables in PHP considered bad practice? If so, why?](https://stackoverflow.com/questions/1557787/are-global-variables-in-php-considered-bad-practice-if-so-why) – csabinho Jan 06 '18 at 06:14
  • Your PHP application lives for only one request. On each request the entire code (that you use/include for that request url) runs and when respondning it cleans up and shuts down. This means you will not have variables that live across requests or that can pollute over to other user requests. Of course someone figured they needed some stored state, so the session system gives you an automatic way to handle assigning a cookie to fetch the correct session array data from a (server side) storage. But normal variables will be wiped clean after the request ends – JimL Jan 06 '18 at 07:19

2 Answers2

3

Global variables can be accessed and altered by any of the php that is running in the current stack. Sometimes it is by other scripts that you did not write which are part of the framework or loaded code libraries.

It is very hard to debug code when values can be modified in many files.

It's not apparent in a simple example of concurrent requests which are all run in a different memory stack, it's in the system at large where globals can become unpredictable.

JasonB
  • 5,747
  • 2
  • 13
  • 25
1

I answer this question:

will the echoed $variable1 be displayed as what the respective users have input to their browser or it will override the first user's input by the last user's input?

The echoed $variable1 will be displayed as what the respective users have input to their browser.

PHP makes thread per request, so different requests have different variables (include global).

I check this post.

As said by JasonB, PHP global variable has a very wide scope, and make code complex.

noymer
  • 201
  • 1
  • 10