- PHP OOP — Inheritance
- Example
- Example Explained
- PHP — Inheritance and the Protected Access Modifier
- Example
- Example
- PHP — Overriding Inherited Methods
- Example
- PHP — The final Keyword
- Example
- Example
- PHP Inheritance
- Introduction to the PHP inheritance
- Add properties and methods to the child class
- Call methods from the parent class
- Inhertiance and UML
- Summary
- Extending PHP classes
- 4 Answers 4
PHP OOP — Inheritance
Inheritance in OOP = 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.
An inherited class is defined by using the extends keyword.
Example
class Fruit public $name;
public $color;
public function __construct($name, $color) $this->name = $name;
$this->color = $color;
>
public function intro() echo «The fruit is name> and the color is color>.»;
>
>
?php
// Strawberry is inherited from Fruit
class Strawberry extends Fruit public function message() echo «Am I a fruit or a berry? «;
>
>
$strawberry = new Strawberry(«Strawberry», «red»);
$strawberry->message();
$strawberry->intro();
?>
Example Explained
The Strawberry class is inherited from the Fruit class.
This means that the Strawberry class can use the public $name and $color properties as well as the public __construct() and intro() methods from the Fruit class because of inheritance.
The Strawberry class also has its own method: message().
PHP — Inheritance and the Protected Access Modifier
In the previous chapter we learned that protected properties or methods can be accessed within the class and by classes derived from that class. What does that mean?
Example
class Fruit public $name;
public $color;
public function __construct($name, $color) $this->name = $name;
$this->color = $color;
>
protected function intro() echo «The fruit is name> and the color is color>.»;
>
>
?php
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
?>
In the example above we see that if we try to call a protected method (intro()) from outside the class, we will receive an error. public methods will work fine!
Let’s look at another example:
Example
class Fruit public $name;
public $color;
public function __construct($name, $color) $this->name = $name;
$this->color = $color;
>
protected function intro() echo «The fruit is name> and the color is color>.»;
>
>
?php
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
?>
In the example above we see that all works fine! It is because we call the protected method (intro()) from inside the derived class.
PHP — Overriding Inherited Methods
Inherited methods can be overridden by redefining the methods (use the same name) in the child class.
Look at the example below. The __construct() and intro() methods in the child class (Strawberry) will override the __construct() and intro() methods in the parent class (Fruit):
Example
class Fruit public $name;
public $color;
public function __construct($name, $color) $this->name = $name;
$this->color = $color;
>
public function intro() echo «The fruit is name> and the color is color>.»;
>
>
?php
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 «The fruit is name>, the color is color>, and the weight is weight> gram.»;
>
>
$strawberry = new Strawberry(«Strawberry», «red», 50);
$strawberry->intro();
?>
PHP — The final Keyword
The final keyword can be used to prevent class inheritance or to prevent method overriding.
The following example shows how to prevent class inheritance:
Example
// will result in error
class Strawberry extends Fruit // some code
>
?>
The following example shows how to prevent method overriding:
Example
class Fruit final public function intro() // some code
>
>
?php
class Strawberry extends Fruit // will result in error
public function intro() // some code
>
>
?>
PHP Inheritance
Summary: in this tutorial, you will learn about the PHP inheritance that allows a class to reuse the code from another class.
Introduction to the PHP inheritance
Inheritance allows a class to reuse the code from another class without duplicating it.
In inheritance, you have a parent class with properties and methods, and a child class can use the code from the parent class.
Inheritance allows you to write the code in the parent class and use it in both parent and child classes.
The parent class is also called a base class or super class. And the child class is also known as a derived class or a subclass.
To define a class inherits from another class, you use the extends keyword.
Suppose that you have a class called BankAccount as follows:
class BankAccount < private $balance; public function getBalance() < return $this->balance; > public function deposit($amount) < if ($amount > 0) < $this->balance += $amount; > return $this; > >
Code language: HTML, XML (xml)
The BankAccount class has the private property $balance and the public methods getBalance() and deposit() .
To declare that the SavingAccount inherits from the BankAccount , you use the extends keyword as follows:
class SavingAccount extends BankAccount
Code language: HTML, XML (xml)
In this example, the SavingAccount can reuse all the non-private properties and methods from the BankAccount class.
The following creates a new instance of the SavingAccount class, calls the deposit() method and shows the balance:
require 'SavingAccount.php'; $account = new SavingAccount(); $account->deposit(100); echo $account->getBalance();
Code language: HTML, XML (xml)
In this example, the SavingAccount class reuses the properties and methods from the BankAccount class.
A child class can reuse properties and methods from the parent class. But the parent class cannot use properties and methods from the child class.
Add properties and methods to the child class
A child class can have its own properties and methods. In the following example, we add the $interestRate property and setInterestRate() method to the SavingAccount class:
class SavingAccount extends BankAccount < private $interestRate; public function setInterestRate($interestRate) < $this->interestRate = $interestRate; > >
Code language: HTML, XML (xml)
Call methods from the parent class
To call a method from the parent class, you use the $this keyword.
The following example defines the addInterest() method that calculates the interest and adds it to the balance:
class SavingAccount extends BankAccount < private $interestRate; public function setInterestRate($interestRate) < $this->interestRate = $interestRate; > public function addInterest() < // calculate interest $interest = $this->interestRate * $this->getBalance(); // deposit interest to the balance $this->deposit($interest); > >
Code language: HTML, XML (xml)
In the addInterest() method, we call the getBalance() method from the BankAccount class for calculating the interest and the deposit() method to add the interest to the balance.
class BankAccount < private $balance; public function getBalance() < return $this->balance; > public function deposit($amount) < if ($amount > 0) < $this->balance += $amount; > return $this; > > class SavingAccount extends BankAccount < private $interestRate; public function setInterestRate($interestRate) < $this->interestRate = $interestRate; > public function addInterest() < // calculate interest $interest = $this->interestRate * $this->getBalance(); // deposit interest to the balance $this->deposit($interest); > > $account = new SavingAccount(); $account->deposit(100); // set interest rate $account->setInterestRate(0.05); $account->addInterest(); echo $account->getBalance();
Code language: HTML, XML (xml)
Inhertiance and UML
You use the open arrow from the child class to the parent class to represent the inheritance relationship. The following UML diagram shows the inheritance relationship between the BankAccount and SavingAccount classes:
Summary
- Inheritance allows a class to reuse the code of another class without duplicating it.
- Use the extends keyword to define one class that inherits from another class.
- A class that inherits another class is called a subclass, a child class, or a derived class. The class from which the subclass inherits is a parent class, a superclass, or a base class.
- A subclass can have its own properties and methods.
- Use $this keyword to call the methods of the parent class from methods in the child class.
Extending PHP classes
I’m still learning how to use classes and I was wondering when should I use the extends keyword (extend a class). Let’s say I have a class that does thing A (and it’s a singleton). Is it ok to extend it to another one that does thing B, even if class B is not really related to class A, but it uses a lot of its methods? Or should I create a new class?
Could you explain in what circumtances you need to extend singleton class ? Maybe there is other design approach. Did you hear about dependency injection pattern ?
4 Answers 4
When it comes to Object-Oriented programming generally a class does a specific task, such as hold user information, or input / output control.
When you have let’s say 1 object that is used to control the output, you can set a method within that object to control the output type, or how a each specific content should be handled, but that would mean that the objects sole purpose has been broken, as it’s now not just sending content, but it’s also manipulating content depending on it’s type.
A way in which we use to over come this is by grouping a set of tasks into a group of classes / objects, example:
The output class would obviously have much more methods but only methods related to ouputting content, such as headers etc, and not the manipulation of the content, then you would have something like:
class HTMLOutput extends Output < public $content_type = 'text/html'; >
and for the manipulation of the content:
class CSSOutput extends Output < public $content_type = 'text/css'; public _send() < if($_SERVER['APP']['Settings']['CSSCompress'] == '1') < $this->_compress_css(); > parent::_send(); > private function _compress_css() < $this->content = ; //Some compression lib > >
This is the main architecture points that I abide by when creating and organizing many grouped classes / objects.