Note: This is a reference question for dealing with variable scope in PHP. Please close any of the many questions fitting this pattern as a duplicate of this one.
What is "variable scope" in PHP? Are variables from one .php file accessible in another? Why do I sometimes get "undefined variable" errors?
Although variables defined inside of a function's scope can not be accessed from the outside that does not mean you can not use their values after that function completes. PHP has a well known
static
keyword that is widely used in object-oriented PHP for defining static methods and properties but one should keep in mind thatstatic
may also be used inside functions to define static variables.What is it 'static variable'?
Static variable differs from ordinary variable defined in function's scope in case that it does not loose value when program execution leaves this scope. Let's consider the following example of using static variables:
Result:
If we'd defined
$counter
withoutstatic
then each time echoed value would be the same as$num
parameter passed to the function. Usingstatic
allows to build this simple counter without additional workaround.Static variables use-cases
Tricks
Static variable exists only in a local function scope. It can not be accessed outside of the function it has been defined in. So you may be sure that it will keep its value unchanged until the next call to that function.
Static variable may only be defined as a scalar or as a scalar expression (since PHP 5.6). Assigning other values to it inevitably leads to a failure at least at the moment this article was written. Nevertheless you are able to do so just on the next line of your code:
Result:
Static function is kinda 'shared' between methods of objects of the same class. It is easy to understand by viewing the following example:
This only works with objects of the same class. If objects are from different classes (even extending one another) behavior of static vars will be as expected.
Is static variable the only way to keep values between calls to a function?
Another way to keep values between function calls is to use closures. Closures were introduced in PHP 5.3. In two words they allow you to limit access to some set of variables within a function scope to another anonymous function that will be the only way to access them. Being in closure variables may imitate (more or less successfully) OOP concepts like 'class constants' (if they were passed in closure by value) or 'private properties' (if passed by reference) in structured programming.
The latter actually allows to use closures instead of static variables. What to use is always up to developer to decide but it should be mentioned that static variables are definitely useful when working with recursions and deserve to be noticed by devs.
I won't post a complete answer to the question, as the existing ones and the PHP manual do a great job of explaining most of this.
But one subject that was missed was that of superglobals, including the commonly used
$_POST
,$_GET
,$_SESSION
, etc. These variables are arrays that are always available, in any scope, without aglobal
declaration.For example, this function will print out the name of the user running the PHP script. The variable is available to the function without any problem.
The general rule of "globals are bad" is typically amended in PHP to "globals are bad but superglobals are alright," as long as one is not misusing them. (All these variables are writable, so they could be used to avoid dependency injection if you were really terrible.)
These variables are not guaranteed to be present; an administrator can disable some or all of them using the
variables_order
directive inphp.ini
, but this is not common behaviour.A list of current superglobals:
$GLOBALS
- All the global variables in the current script$_SERVER
- Information on the server and execution environment$_GET
- Values passed in the query string of the URL, regardless of the HTTP method used for the request$_POST
- Values passed in an HTTP POST request withapplication/x-www-form-urlencoded
ormultipart/form-data
MIME types$_FILES
- Files passed in an HTTP POST request with amultipart/form-data
MIME type$_COOKIE
- Cookies passed with the current request$_SESSION
- Session variables stored internally by PHP$_REQUEST
- Typically a combination of$_GET
and$_POST
, but sometimes$_COOKIES
. The content is determined by therequest_order
directive inphp.ini
.$_ENV
- The environment variables of the current scriptWhat is "variable scope"?
Variables have a limited "scope", or "places from which they are accessible". Just because you wrote
$foo = 'bar';
once somewhere in your application doesn't mean you can refer to$foo
from everywhere else inside the application. The variable$foo
has a certain scope within which it is valid and only code in the same scope has access to the variable.How is a scope defined in PHP?
Very simple: PHP has function scope. That's the only kind of scope separator that exists in PHP. Variables inside a function are only available inside that function. Variables outside of functions are available anywhere outside of functions, but not inside any function. This means there's one special scope in PHP: the global scope. Any variable declared outside of any function is within this global scope.
Example:
$foo
is in the global scope,$baz
is in a local scope insidemyFunc
. Only code insidemyFunc
has access to$baz
. Only code outsidemyFunc
has access to$foo
. Neither has access to the other:Scope and included files
File boundaries do not separate scope:
a.php
b.php
The same rules apply to
include
d code as applies to any other code: onlyfunction
s separate scope. For the purpose of scope, you may think of including files like copy and pasting code:c.php
In the above example,
a.php
was included insidemyFunc
, any variables insidea.php
only have local function scope. Just because they appear to be in the global scope ina.php
doesn't necessarily mean they are, it actually depends on which context that code is included/executed in.What about functions inside functions and classes?
Every new
function
declaration introduces a new scope, it's that simple.(anonymous) functions inside functions
classes
What is scope good for?
Dealing with scoping issues may seem annoying, but limited variable scope is essential to writing complex applications! If every variable you declare would be available from everywhere else inside your application, you'd be stepping all over your variables with no real way to track what changes what. There are only so many sensible names you can give to your variables, you probably want to use the variable "
$name
" in more than one place. If you could only have this unique variable name once in your app, you'd have to resort to really complicated naming schemes to make sure your variables are unique and that you're not changing the wrong variable from the wrong piece of code.Observe:
If there was no scope, what would the above function do? Where does
$bar
come from? What state does it have? Is it even initialized? Do you have to check every time? This is not maintainable. Which brings us to...Crossing scope boundaries
The right way: passing variables in and out
The variable
$bar
is explicitly coming into this scope as function argument. Just looking at this function it's clear where the values it works with originate from. It then explicitly returns a value. The caller has the confidence to know what variables the function will work with and where its return values come from:Extending the scope of variables into anonymous functions
The anonymous function explicitly includes
$foo
from its surrounding scope. Note that this is not the same as global scope.The wrong way:
global
As said before, the global scope is somewhat special, and functions can explicitly import variables from it:
This function uses and modifies the global variable
$foo
. Do not do this! (Unless you really really really really know what you're doing, and even then: don't!)All the caller of this function sees is this:
There's no indication that this function has any side effects, yet it does. This very easily becomes a tangled mess as some functions keep modifying and requiring some global state. You want functions to be stateless, acting only on their inputs and returning defined output, however many times you call them.
You should avoid using the global scope in any way as much as possible; most certainly you should not be "pulling" variables out of the global scope into a local scope.