This site is mobile accessible. Press the "Tap Here" button to use a different font-size.


Smartphone icons created by Freepik - Flaticon

PHP Inheritance

Inheritance and the Protected Access Modifier

<?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? "; 
  }
}

// Try to call all three methods from outside class
$strawberry = new Strawberry("Strawberry", "red");  // OK. __construct() is public
$strawberry->message(); // OK. message() is public
$strawberry->intro(); // ERROR. intro() is protected
?>

The above code causes a fatal error which stops the script and prevent the rest of the page loading completely.

Am I a fruit or a berry?