Skip to content

Latest commit

 

History

History
109 lines (81 loc) · 2.76 KB

5.md

File metadata and controls

109 lines (81 loc) · 2.76 KB

Lesson 5: Inheritance

New Keywords:

  • extends
  • parent
  • protected

Inheritance is a programming construct that software developers use to establish an "is-a" relationship between categories. Inheritance enables us to derive more-specific categories from more-generic ones. The more-specific category is a kind of the more-generic category. For example, a dog is a kind of mammal, and a bicycle is a kind of vehicle.

PHP supports class extension via the extends keyword, and specifies a parent-child relationship between two classes

<?php

class ContentEntityBase {
  // ... Other properties and methods.
  
  public function id() {
    return $this->getEntityKey('id');
  }
}

class Node extends ContentEntityBase {
  // ... Other properties and methods.
}

Parent

You may find yourself writing code that refers to variables and functions in base classes. This is particularly true if your derived class is a refinement or specialization of code in your base class. Parent properties and methods can be accessed with the parent keyword and the scope resolution operator.

<?php

class Node extends ContentEntityBase {
  // ... Other properties and methods.
  
  public function access($operation = 'view', AccountInterface $account = NULL, $return_as_object = FALSE) {
    // This override exists to set the operation to the default value "view".
    return parent::access($operation, $account, $return_as_object);
  }
}

Protected: visibility

Another level of visibility (information hiding) is "protected", which means that a protected property or method can be accessed only from within the class defining it, or any subclassses. In contrast, a private property/method is only visible to the class defining it.

<?php

class A {
  public $public = 'Public';
  protected $protected = 'Protected';
  private $private = 'Private';

  public function testVisibilityA() {
     echo $this->public;
     echo $this->protected;
     echo $this->private;
  }
}

// --

$a = new A();
echo $a->public; // Public
echo $a->protected; // Fatal error
echo $a->private; // Fatal error
$a->testVisibilityA(); // Public, Protected, Private

// --

class B extends A {

  public function testVisibilityB() {
     echo $this->public;
     echo $this->protected;
     echo $this->private;
  }
}

// --

$b = new B();
echo $b->public; // Public
echo $b->protected; // Fatal error
echo $b->private; // Fatal error
$b->testVisibilityA(); // Public, Protected, Private
$b->testVisibilityB(); // Fatal error: subclass can't access $this->private

Exercises:

  • Add a method "sayHi()" to the Person class.
  • Create two sub-classes "Developer" and "Designer" that extend the Person class.
  • Add a method "work()" to each of those subclasses.
  • Use "parent" in a sub-class method.