In PHP4 all the methods and variables in an Object can be accessed from outside the object - this can be rephrased as methods and variables are always public. PHP5 introduces 3 modifiers to control the access to variables and methods: Public, Protected and Private.
Public: The method/variable can be accessed from outside the class.
Private: Only methods in the same class can access private methods or variables.
Protected: Only methods in the same class or derived classes can access proteted methods or variables.
<?php
class foo {
private $x;
public function public_foo() {
print("I'm public");
}
protected function protected_foo() {
$this->private_foo(); //Ok because we are in the same class we can call private methods
print("I'm protected");
}
private function private_foo() {
$this->x = 3;
print("I'm private");
}
}
class foo2 extends foo {
public function display() {
$this->protected_foo();
$this->public_foo();
// $this->private_foo(); // Invalid! the function is private in the base class
}
}
$x = new foo();
$x->public_foo();
//$x->protected_foo(); //Invalid cannot call protected methods outside the class and derived classes
//$x->private_foo(); //Invalid private methods can only be used inside the class
$x2 = new foo2();
$x2->display();
?>













