aniesh82 Posted July 31, 2008 Share Posted July 31, 2008 Hi all, I am new to oops concept in php and when I started studying, I have a doubt about the visibility usage. Can someone helps me to find out the bug in the following code? This code below will works fine, if I add a visibility to the variable declaration time.. Example: public $var2=10; <?php CLASS ABC { $var2 = 10; function show() { echo "<BR>VAR2 is:".$this->var2; } } $objABC = NEW ABC(); $objABC->show(); ?> Also I have another question. Why I can't use the variable directly inside the function like below? class abc { public $var=100; function myFunction() { echo $var; } } Quote Link to comment Share on other sites More sharing options...
DarkWater Posted July 31, 2008 Share Posted July 31, 2008 First of all, what version of PHP do you use? Quote Link to comment Share on other sites More sharing options...
aniesh82 Posted July 31, 2008 Author Share Posted July 31, 2008 PHP Version 5.2.4 Quote Link to comment Share on other sites More sharing options...
coder_ Posted July 31, 2008 Share Posted July 31, 2008 Ok, so basic synthax of OOP PHP5 <?php class Tmp { public $tmp; public function __construct() {} } $tmp is a property of object Tmp and is being accessed throught "locked variable" $this. Like this: $this->tmp; So inside class methods object is represented by $this. Quote Link to comment Share on other sites More sharing options...
mbeals Posted July 31, 2008 Share Posted July 31, 2008 #1 in a class statement you have to initialize attributes with visibility, otherwise php doesn't know what is allowed to access it. Once you get the hang of it, you will start to see the importance. #2 Variable scope in a function is the same whether you are writing a function i OOP or in procedural. In a function block, all variables are local to that function. IE: <?php $foo = 1; function printFoo(){ echo $foo; } ?> will not output anything in any form of php, as $foo is not defined in the function's scope. This also means you can declare variables in method definitions without worrying about overriding : <?php class newClass{ private $foo = 'test'; function printFoo(){ $foo = 1; $bar = 2; echo $foo."\n"; echo $this->foo."\n"; echo $bar."\n"; } } ?> So calling the printFoo() method would print: 1 test 2 The reference to $foo in the first echo statement was inside the scope of the method. You have to use the $this variable to access the scope of the class. Sort of like (but not really) using global in a procedural function. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.