i

PHP Tutorial

PHP-Inheritance and Protected Access Modifier

As we discussed that a derived class can access protected properties and methods of the parent class. Let us see via example:

class Doctor {
  public $name;
  public function __construct($name) {
    $this->name = $name;
  }
  protected function intro() {
    echo "The Doctor name is {$this->name}

}"; } }

// Surgeon is inherited from Doctor
class Surgeon extends Doctor{
  public function message() {
    echo "The surgeon are doctors experienced in surgery";
  }
}
$Surgeon1 = new Surgeon1("Sebastian"); //public construct function works fine.
$Surgeon1 ->message(); // public method works fine
$Surgeon1 ->intro(); // gives error as intro() is protected method in parent class.
?>

However, you can use the protected method inside a derived class as below:

class Doctor {
  public $name;
  public function __construct($name) {
    $this->name = $name;
  }
  public function intro() {
    echo "The Doctor name is {$this->name}

}"; } }

// Surgeon is inherited from Doctor
class Surgeon extends Doctor{
  public function message() {
    echo "The surgeon are doctors experienced in surgery";

    $this -> intro(); // Calling protected method inside derived class works fine.
  }
}
$Surgeon1 = new Surgeon1("Sebastian");
$Surgeon1 ->message();  // message is public and intro() inside message function is //used inside derived class. So, it works fine.

?>