PHP OOP - Moștenire. PHP - Metode ereditare de moștenire. Metode moștenite. Clasa child. Metodele __construct() și intro().

PHP - Metode ereditare de moștenire (PHP - Overriding Inherited Methods)

Metodele moștenite (Inherited methods) pot fi anulate prin redefinirea metodelor (folosiți același nume) în clasa child (copil).

Priviți exemplul de mai jos. Metodele __construct() și intro() din clasa child (copil) (Strawberry) vor înlocui metodele __construct() și intro() din clasa parent (părinte) (Fruit):

Exemplu:
 
<?php
class Fruit {
  public $name;
  public $color;
  public function __construct($name, $color) {
    $this->name = $name;
    $this->color = $color;
  }
  public function intro() {
    echo "Fructul este {$this->name} și culoarea este {$this->color}.";
  }
}

class Strawberry extends Fruit {
  public $weight;
  public function __construct($name, $color, $weight) {
    $this->name = $name;
    $this->color = $color;
    $this->weight = $weight;
  }
  public function intro() {
    echo "Fructul este {$this->name}, culoarea este {$this->color}, și greutatea este {$this->weight} gram.";
  }
}

$strawberry = new Strawberry("Strawberry", "red", 50);
$strawberry->intro();
?>