Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding variable scopes in php

Tags:

scope

php

echo "Point1, a=".$a."\n";
echo "Point1, b=".$b."\n";
if(1<2)
    {
        $a = 6; 
        $b['link'] = "here";
        echo "Point2, a=".$a."\n";
        echo "Point2, b[link]=".$b['link']."\n";
    }
echo "Point3, a=".$a."\n";
echo "Point3, b[link]=".$b['link']."\n";

Why does the above code print out the following?

Point1, a=
Point1, b=
Point2, a=6
Point2, b[link]=here
Point3, a=6
Point3, b[link]=here

In my understanding, the scope of $a and $b should end within the curly braces { }!

like image 333
tzmatt7447 Avatar asked Jul 02 '26 06:07

tzmatt7447


2 Answers

In my understanding, the scope of $a and $b should end within the curly braces { }!

Only functions and methods have their own, local scope. Other control structures (loops, conditions...) do not.

Variable scope in the PHP manual

like image 132
Pekka Avatar answered Jul 03 '26 21:07

Pekka


The first $a and $b would actually throw a warning, undefined index as they haven't been declared before being output.

like image 28
MRW Avatar answered Jul 03 '26 22:07

MRW



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!