+1 vote

What is "variable scope" in PHP? Are variables from one .php file accessible in another? Why do I sometimes get "undefined variable" errors?

1 Answer

0 votes
selected by
Best answer

What 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.


$foo = 'bar';
function myFunc() {
    $baz = 42;}

$foo is in the global scope, $baz is in a local scope inside myFunc. Only code inside myFunc has access to $baz. Only code outside myFunc has access to $foo. Neither has access to the other:

$foo = 'bar';
function myFunc() {
    $baz = 42;
    echo $foo;  // doesn't work
    echo $baz;  // works}
echo $foo;  // works
echo $baz;  // doesn't work
Scope and included files

File boundaries do not separate scope:


$foo = 'bar';


<?php include 'a.php'; echo $foo; // works!

The same rules apply to included code as applies to any other code: only functions separate scope. For the purpose of scope, you may think of including files like copy and pasting code:


function myFunc() {
    include 'a.php';
    echo $foo;  // works}
echo $foo;  // doesn't work!

In the above example, a.php was included inside myFunc, any variables inside a.php only have local function scope. Just because they appear to be in the global scope in a.php doesn't necessarily mean they are, it actually depends on which context that code is included/executed in.

Welcome to Memory Exceeded, where you can ask questions and receive answers from other members of the community.