12-21-2007, 02:39 PM
|
#3 (permalink)
|
|
Wizard
Join Date: Sep 2007
Posts: 1,298
Thanks: 17
|
As taken from http://tips.justanotherportfolio.com/?page_id=6
Visibility
Variables in classes can be set to three different types of visibility Visibility tells the program who can see what. The three types are:
Public: Anyone can access it, outside, inside and child classes.
Example: Any above code, anything can access it.
Protected: Only functions within that class and child classes can access it
example: <?
class calc_functions
{
protected function add($x,$y)
{
return $x + $y;
}
protected function subtract($x,$y)
{
return $x - $y;
}
}
class calc extends calc_functions
{
public function display()
{
echo “100 + 100 is “.parent::add(100,100).”<br />200 - 100 is “.parent::subtract(200,100);
}
}
$math = new calc;
$math->display();
?>
As you can see, the function it extended to are able to access calc_function’s functions, but if we where to make an instance of calc_function and try to call $instance->add(100,100); you would get a fatal error.
Private: Only functions within that class can access it.
Example: <?
class calc
{
protected function add($x,$y)
{
return $x + $y;
}
protected function subtract($x,$y)
{
return $x - $y;
}
public function display()
{
echo “100 + 100 is “.calc::add(100,100).”<br />200 - 100 is “.calc::subtract(200,100);
}
}
$math = new calc;
$math->display();
?>
As you can see here, those could be accessed by the functions within the class, if we where to create a child class to inherit it, neither of those functions could be accessed by it. The same applies to outside the class.
Note: When using var to declare a variable in a class, it sets it to public, this was only continued from php4 (which didn’t have visibility settings) for code compatibility reasons. It is deprecated and probably shouldn’t be used, but it doesn’t make a difference unless you need to use private or protected. Functions left without a visibility definition are public, I generally don’t define public in my code, it doesn’t make a difference.
Last edited by Village Idiot : 12-21-2007 at 07:08 PM.
|
|
|
|