Protected
Properties and methods marked as protected are accessible only through the object that owns them, whether or not they are declared in that object's class or have descended from a parent class. Consider the following code:
Ex. -> class A {
public $Name;
private function getName( ) {
return $this->Name;
}
}
class B extends A {
public function say( ) {
print "'Hello', says " . $this->getName( );
}
}
$p = new B;
$p->Name = "XYZ";
$p->say( );
In that code, the class B extends from class A, class A has a public property $Name and a private method getName( ), and class B has a public method called say( ). So, we create a B, give it a $Name value of "XYZ" (the $Name property comes from the Dog class), then ask it to say( ). The say( ) method is public, which means we can call it as shown above, so this is all well and good.
However, the say( ) method calls the getName( ) method, which is part of the A class and was marked private this will stop the script from working, because private properties and methods cannot be accessed from inherited classes. That is, we cannot access private Dog methods and properties from inside the B class.
Now try changing getName( ) to protected, and all should become clearthe property is still not available to the world as a whole, but handles inheritance as you would expect, meaning that we can access getName( ) from inside B.
0 comments:
Post a Comment