Jan 29, 2013

PHP: Weird scope of variables

First of all, this post is simply a note that reminds me of something basic but important in PHP programming....


In PHP, except member variables of a class, all the PHP variables are available once it is assigned with some values even if it's surrounded by a set of brackets.

Generally, brackets in C/C++ has the effect of limiting the affective scope of a variable.
Considering the following two code segments of func1 and func2.

//test1.cpp
void func1()
{
    int a = 5;
    a++;
}

//test2.cpp
void func1()
{
    if(true)
    {
        int a = 5;
    }
    a++;
}

If you try to compile these segments, the compiler will throw the following error message:
    test.cpp: In function ‘void func()’:
    test.cpp:7: error: ‘a’ was not declared in this scope

As you can see, the declarations surrounded by a set of brackets will be treated as a local variable that lives and existed in the bracket.

But in PHP, the following code segments of func3 and func4 will execute without errors and and return the same value of 6.


function func3()
{
    $a = 5;
    $a++;

    return $a;
}
function func4()
{
    if(true)
    {
        $a = 5;
    }
    $a++;

    return $a;
}

 Base on theses examples, I have to be careful in writing PHP code and try to avoid mistakened variable rewriting......

No comments:

Post a Comment