PHP Variable Scope (and how it differs from Javascript)

After learning about variable scope, the scope chain and name space in Javascript, I just wanted to sum up succinctly and briefly my understanding of PHP Variable Scope and how it differs from Javascript for those who might be wondering or learning about the topic.

The main difference between Javascript and PHP variable scope is concerning their accessibility inside and outside of functions:

  • Javascript: Global variables are visible inside functions.  There is an outer reference feature built in the engine that allows for variables in the outer environment to be visible and available in the execution context of a function.
  • PHP: Global variables do not have scope inside functions (unless you use the keyword ‘global‘ preceding the global variable being referenced inside the function to access them).  Variables inside functions, conversely, do not have global scope and are not visible outside of their parent function (you can declare a variable inside a function as global by again using the keyword ‘global‘.)

There is an excellent post on Stackoverflow here discussing variable scope in PHP in great detail.

A key ‘quirk’ to note that might be confusing is to understand that, in PHP, if a variable inside a function is created and declared as global without having existed as a global beforehand, then it’s value will only be retained inside that function, and outside of the function it will be empty.  If the global variable has already been declared in the global space, then referencing it inside a function with the ‘global‘ keyword will allow you to assign it a value that sticks globally.

I didn’t realize how simple variable scope in PHP was.  It probably helps that I already understand variable scope in Javascript fairly well, which is more complex involving Closures, Execution Contexts and the Execution Stack, so getting the gist of it in PHP is more straight-forward in comparison.

Be sure to check out my GitHub page to see what I’m working on currently.  I’m pushing a lot of code and updates and am working feverishly to make progress.  Anyways, I hope this little article helped boil down variable scope in PHP and some of the differences between it and that of Javascript.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.