Object Oriented

Inheritance

PHP

 

Inheriting

PHP 5
class Person {
  public function __construct($name) {
    $this->name = $name;
  }

  public function greet() {
    print("Hi! I'm " . $this->name);
  }
}

class Teacher extends Person {
  public function __construct($name, $grade) {
    parent::__construct($name);
    $this->grade = $grade;
  }
}

Classes can inherit methods and properties of another class.

In this example, the Teacher class inherits the $name property and greet() method from the Person class.

$teacher1 = new Teacher('Alice', 2);

$name = $teacher1->name;  // Alice
$teacher1->greet();       // Hi! I'm Alice

You need to explicitly call the Parent (Person) Constructor from the children (Teacher) Constructors.

 

Overriding Methods

PHP 5
class Person {
  public function __construct($name) {
    $this->name = $name;
  }

  public function greet() {
    print("Hi! I'm " . $this->name);
  }
}

class Teacher extends Person {
  public function __construct($name) {
    parent::__construct($name);
  }
  
  public function greet() {
    print("Hello! I am " . $this->name);
  }
  
  public function greet2() {
    parent::greet();
  }
}

Inherited methods from a parent class can be overridden in the children's classes.

Overriding methods is more like extending the definition rather than replacing them.

$teacher1 = new Teacher('Alice');

$teacher1->greet();   // Hello! I am Alice
$teacher1->greet2();  // Hi! I'm Alice