Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, an odd variable scope?

Tags:

scope

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,

like image 772
Shyam Avatar asked Apr 21 '11 11:04

Shyam


People also ask

Are PHP variables scoped?

PHP has three different variable scopes: local. global. static.

Which is not a variable scope in PHP?

There are only two scopes available in PHP namely local and global scopes. When a variable is accessed outside its scope it will cause PHP error Undefined Variable.

What are different types of variable scopes in PHP?

PHP has three types of variable scopes: Local variable. Global variable. Static variable.

What are the four types of variable scopes?

You will learn about the four different scopes with the help of examples: local, enclosing, global, and built-in. These scopes together form the basis for the LEGB rule used by the Python interpreter when working with variables.


1 Answers

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.

like image 56
mario Avatar answered Oct 26 '22 16:10

mario