Jump to content

class member declaration & visibility


aniesh82

Recommended Posts

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;
            }
}

 

Link to comment
https://forums.phpfreaks.com/topic/117452-class-member-declaration-visibility/
Share on other sites

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.

#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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.