what is the variable scope of a class member variable?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
kknight
Forum Newbie
Posts: 4
Joined: Tue Nov 15, 2005 7:45 pm
Location: CA, USA

what is the variable scope of a class member variable?

Post 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.
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post 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;
User avatar
staniszczak
Forum Newbie
Posts: 13
Joined: Wed Oct 05, 2005 1:39 pm
Location: Radomsko, Poland

Post 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
Post Reply