PHP Variable Scope

Reference: What is variable scope, which variables are accessible from where and what are undefined variable errors?

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

Scope and included files

File boundaries do not separate scope:

a.php

<?php

$foo = 'bar';

b.php

<?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:

c.php

<?php

function myFunc() {
include 'a.php';

echo $foo; // works
}

myFunc();

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.

What about functions inside functions and classes?

Every new function declaration introduces a new scope, it's that simple.

(anonymous) functions inside functions

function foo() {
$foo = 'bar';

$bar = function () {
// no access to $foo
$baz = 'baz';
};

// no access to $baz
}

classes

$foo = 'foo';

class Bar {

public function baz() {
// no access to $foo
$baz = 'baz';
}

}

// no access to $baz

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:

function foo() {
echo $bar;
}

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

function foo($bar) {
echo $bar;
return 42;
}

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:

$baz   = 'baz';
$blarg = foo($baz);

Extending the scope of variables into anonymous functions

$foo = 'bar';

$baz = function () use ($foo) {
echo $foo;
};

$baz();

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:

$foo = 'bar';

function baz() {
global $foo;
echo $foo;
$foo = 'baz';
}

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:

baz(); // outputs "bar"
unset($foo);
baz(); // no output, WTF?!
baz(); // outputs "baz", WTF?!?!!

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.

Variable scope in for-loop and while-loop

The $a on line 1 and the $a in the foreach() loop is one and the same object. And after the loop ends, $a has the value 3, which is echoed in the last statement.

According to php.net:

For the most part all PHP variables only have a single scope.

Only in a function does the variable scope is different.

This would produce your desired result '231':

$a = '1';
$c = array('2', '3');
function iterate($temp)
{
foreach($temp as $a)
echo $a ;
}
iterate($c)
echo $a;

Because in the iterate() function, $a is independent of the $a of the calling code.

More info: http://php.net/manual/en/language.variables.scope.php

PHP variable life cycle/ scope

In PHP control statements have no separate scope. They share the scope with the outer function or the global scope if no function is present. (PHP: Variable scope).

$foo = 'bar';

function foobar() {
$foo = 'baz';

// will output 'baz'
echo $foo;
}

// will output 'bar'
echo $foo;

Your variables will have the last value assigned within the control structure. It is good practice to initialize the variable before the control structure but it is not required.

// it is good practice to declare the variable before
// to avoid undefined variables. but it is not required.
$foo = 'bar';
if (true == false) {
$foo = 'baz';
}

// do something with $foo here

Namespaces do not affect variable scope. They only affect classes, interfaces, functions and constants (PHP: Namespaces Overview). The following code will output 'baz':

namespace A { 
$foo = 'bar';
}

namespace B {
// namespace does not affect variables
// so previous value is overwritten
$foo = 'baz';
}

namespace {
// prints 'baz'
echo $foo;
}

PHP Variable Scope understanding

The local variable is being overwritten with the statement global and since they are sharing the same variable name, you lost reference to it.

But by doing this, you can use both:

$x = 5;

function scopeTest($x) {
echo $GLOBALS['x'], $x; // 54
}

scopeTest(4);

Or.. just rename the local variable

function scopeTest($y) {
global $x;
echo $x, $y;
}

php variable scope

If you do while(true) you will not get out of the while, so it wouldn't matter. But if you would have a real expression, something like this (this is a useless example, i know)

$i=0
while($i<10){
$var = "yes , it is a test!";
$i++;
}
printf($var);

Will just work.
There is no special "while" variable scope, the printf will print your string. check : http://php.net/manual/en/language.variables.scope.php

PHP variable scope between code blocks

You're putting too much meaning in the php code blocks.

It's not something that global.

These blocks belong to the same PHP script. It's just a neat way to output HTML, nothing more. You can substitute it with echoing the HTML and there will not be the slightest difference.

The whole PHP script is being executed at once, not in iterations, as you probably picture this, thinking that PHP blocks are being executed server-side, then HTML blocks client-side, and then back to PHP blocks on the server side and so on. That's wrong.

The whole PHP script is being executed on the server side, resulting with pure HTML in the browser, and then dies.

That's why you can't program both an HTML form and its handler in the same PHP script by just placing the latter one right after the former. You have to make another call to the server to make the handler work. It will be another call completely, another instance of the same script, knowing nothing of the previous call which is long dead already. And that's another thing you have to know about PHP:

PHP script execution is atomic. It's not like a desktop application constantly running in your browser, or even a daemon with persistent connection to your desktop application. It's more like a command-line utility - doing its job and exits. It runs discretely:

  1. a browser makes a call
  2. PHP wakes up, creates an HTML page, sends it to the browser and dies
  3. Browser renders that HTML and shows it to the user.
  4. User clicks a link
  5. a browser makes a call
  6. another PHP instance, knowing nothing of the previous call, wakes up and so on

PHP variable scope within Try/Catch block

Your code is valid. Variable scope in PHP is by function, not block. So you can assign a variable inside the try block, and access it outside, so long as they're in the same function.



Related Topics



Leave a reply



Submit