Public Members:
Unless you specify otherwise, properties and methods of a class are public. That is to say, they may be accessed in three possible situations:- From outside the class in which it is declared
- From within the class in which it is declared
- From within another class that implements the class in which it is declared
Private members:
By designating a member private, you limit its accessibility to the class in which it is declared. The private member cannot be referred to from classes that inherit the class in which it is declared and cannot be accessed from outside the class.A class member can be made private by using private keyword infront of the member.
class MyClass {
private $car = "skoda";
$driver = "SRK";
function __construct($par) {
// Statements here run every time
// an instance of the class
// is created.
}
function myPublicFunction() {
return("I'm visible!");
}
private function myPrivateFunction() {
return("I'm not visible outside!");
}
}
When MyClass class is inherited by another class using
extends, myPublicFunction() will be visible, as will $driver. The
extending class will not have any awareness of or access to
myPrivateFunction and $car, because they are declared private.Protected members:
A protected property or method is accessible in the class in which it is declared, as well as in classes that extend that class. Protected members are not available outside of those two kinds of classes. A class member can be made protected by using protected keyword infront of the member.Here is different version of MyClass:
class MyClass {
protected $car = "skoda";
$driver = "SRK";
function __construct($par) {
// Statements here run every time
// an instance of the class
// is created.
}
function myPublicFunction() {
return("I'm visible!");
}
protected function myPrivateFunction() {
return("I'm visible in child class!");
}
}

No comments:
Post a Comment