When a class derives from another class. The child class will inherit all the public and protected properties and methods from the parent class. In addition, it can have its own properties and methods.
<?php class Fruit { public $name; protected $color; private $size; public function __construct($name, $color, $size) { $this->name = $name; $this->color = $color; $this->size = $size; } public function intro() { echo "The fruit is {$this->name} and the color is {$this->color}."; } } // Strawberry is inherited from Fruit class Strawberry extends Fruit { public function message1() { echo "Am I a fruit or a {$this->color} berry? "; } public function message2() { echo "Am I a fruit or a {$this->size} berry? "; } } $strawberry = new Strawberry("Strawberry", "red", "300"); $strawberry->message1(); $strawberry->message2(); // Error $strawberry->intro(); ?>
<?php class Fruit { public $name; public $color; public function __construct($name, $color) { $this->name = $name; $this->color = $color; } protected function intro() { echo "The fruit is {$this->name} and the color is {$this->color}."; } } class Strawberry extends Fruit { public function message() { echo "Am I a fruit or a {$this->color} berry? "; } } $strawberry = new Strawberry("Strawberry", "red"); // OK. __construct() is public $strawberry->message(); // OK. message() is public $strawberry->intro(); // ERROR. intro() is protected ?>
<?php class Fruit { public $name; public $color; public function __construct($name, $color) { $this->name = $name; $this->color = $color; } protected function intro() { echo "The fruit is {$this->name} and the color is {$this->color}."; } } class Strawberry extends Fruit { public function message() { echo "Am I a fruit or a berry? "; // Call protected method from within derived class - OK $this->intro(); } } $strawberry = new Strawberry("Strawberry", "red"); // OK. __construct() is public $strawberry->message(); // OK. message() is public and it calls intro() (which is protected) from within the derived class ?>