PHP,一个奇怪的变量范围?

This more a question about the why then 'how-to', yet it has been annoying me for some days now. Currently I am doing some work with CodeIgniter and going back to PHP temporarily from Ruby, bugs me about the following scoping magic.

<?php $query = $this->db->get('articles', 2);
        if ($query->num_rows() > 0)
        {
           foreach ($query->result_array() as $row)
           {
              $data[] = $row; # <-- first appearance here
           }
        return $data; # <--- :S what?!
        } 

As you can see, I am not exactly a PHP guru, yet the idea of local scope bugs me that outside the foreach loop the variable is 'available'. So I tried this out inside a view:

<?php

    if($a==1)
    {
    $b = 2;
    }
    echo $b;
?>

Which result in an error message:

Message: Undefined variable: b

The PHP manual tells about the local scoping, yet I am still wondering why this happens and if there are special rules I do not know about. And it scares me :)

Thanks for sharing ideas,

Only functions create a new local scope. Curly braces by themselves do not. Curly braces are just an auxillary construct for other language structures (if, while or foreach).

And whereever you access any variable in a local scope doesn't matter. The local scope is an implicit dictionary behind the scenes (see get_defined_vars). You might get a debug notice by accessing previously undefined variables, but that's about it.

In your specific example it seems, you are even just operating in the global scope.

foreach does not create any variable scope in PHP so it is natural if variable is available outside foreach

for the second question the $a is not equal to the 1 hence $b is not initialized and throw notice when you access outside. If you assign value 1 to $a and test it you will wonder the notices will gone.

Here is nothing like scope.

Shyam, you are using a scripting language, not C++. It is typical for scripting languages like PHP or JavaScript not to have different scopes for each code block. Instead there is one scope for the whole function. This is actually quite handy if you consider your first example, but you obviously need to be careful as can be seen in your second one.

is $a equals to 1? If not $b=2 will never be evaluated!

See: http://php.net/manual/en/language.variables.scope.php

In php curly braces don't necessarily define a new scope for variables. (your first example)

In your 2nd example, $b is only set on a specific condition. So it is possible to be 'undefined' if this condition is not met.

Actually your first method should be giving you an error too.

You're using a variable that hasn't been declared as an array. I can't understand why you didn't get an error for that.

PHP doesn't have block scope, so whether it's inside IF or FOREACH is irrelevant. If it's available inside the method, you can use it inside the method.