Page 1 of 1

what is the variable scope of a class member variable?

Posted: Wed Nov 16, 2005 5:09 pm
by kknight
twigletmac | Please use

Code: Select all

tags when posting PHP code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]

What is the variable scope of a class member variable? Is it the same as the function variable or a script variable?

For example, foo.php:

Code: Select all

1.   <? 
2.       $a = 1;
3.       class bar {
4.           $a = 2;
5.           function test() {
6.               global $a;
7.               $a = 3;
8.           }
9.        }
10.  ?>
Is the variable $a at line 2 the same varialbe $a at line 4?
Which $a is used at line 7, the one at line 2 or the one at line 4?

Thanks.

Posted: Wed Nov 16, 2005 5:15 pm
by Jenk
2 and 7 are the same, because of line 6.


Line 4 is syntactically incorrect (should read var $a = 2 for php4 syntax)

For line 7 to access line 4, it would need to read $this->a = 3;

Posted: Wed Nov 16, 2005 5:20 pm
by staniszczak
twigletmac | Please use

Code: Select all

tags when posting PHP code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]

Look at this (I correct you're mistake and modifying line:

Code: Select all

$a = 3;
to:

Code: Select all

$a += 3;
for better visible result:

Code: Select all

<?
    $a = 1;
    class bar {
        var $a = 2;
        function test() {
            global $a;
	    echo "Function test() 1: $a<br>";
            $a += 3;
	    echo "Function test() 2: $a<br>";
        }
        function test2() {
	    echo "Function test2() 1: {$this->a}<br>";
            $this->a += 3;
	    echo "Function test2() 2: {$this->a}<br>";
        }
     }


$class = new bar();
$class->test();
echo "Outer 1: $a <br><br>";

bar::test();
echo "Outer 2: $a <br><br>";


$class->test2();
echo "Outer 3: $a <br>";
?>
One line of code works like a thousands words;-)

Best regards,
Marcin Staniszczak