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.
Example:
<?php
$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:
<?php
$foo ='bar';function myFunc(){
$baz =42;
echo $foo;// doesn't work
echo $baz;// works}
echo $foo;// works
echo $baz;// doesn't work