Broad Network


Inheritance in PHP Classes and Objects

Classes and Objects in PHP - Part 3

Foreword: In this part of the series, I talk about inheritance in PHP classes and objects.

By: Chrysanthus Date Published: 24 Nov 2018

Introduction

This is part 3 of my series, Classes and Objects in PHP. In this part of the series, I talk about inheritance in PHP classes and objects. You should have read the previous parts of the series before coming here, as this is the continuation.

New Members
A member is a property or a method. You can have a class with its members. Then you want a new class that will have those same members and new members. Are you going to describe (define) a new class retyping the same old members of the existing class plus new members? PHP exists in such a way that you can have a class with its members and then a new related class with the same members as those of the existing class and with its own new members. So, if you want a class that simply has extra members in addition to what an existing class has, you inherit it (see below) from the existing class, adding the new members.

Example
The following code shows a class with two properties and one method. The method adds the values of the two properties:

<?php

    class Calculator
        {
            public $num1;
            public $num2;

            function __construct($param0, $param1)
                {
                    $this->num1 = $param0;
                    $this->num2 = $param1;
                }

            public function add()
                {
                    $sum = $this->num1 + $this->num2;
                    return $sum;
                }
        }

        $myObject = new Calculator(6, 7);
        $result = $myObject->add();
        echo $result;

?>

Imagine that you want a class that would square a sum (a sum is the addition of two values) and add a fixed value (say 5) to the square. We already have a class that does summing of two values. So, we can derive a class from this existing class. The derived class is the inherited class. It will have an additional property, which holds the fixed value (5). It will have an additional method that squares the sum and adds the fixed value. It inherits the two properties and the add() method of the existing class. The syntax to derive one class from another is:

    class derivedClassName extends baseClassName
        {
            //new members
        }

You begin with the reserved word, class. This is followed by the name of the derived (inherited) class. Then you have the reserved word, extends. Next you have the name of the existing class. The existing class is called the base class or the parent class. We say the derived class is inherited from the parent class. After the parent class name is typed above, you have to describe (code) the derived class (new properties and methods) within curly braces. The following code shows how you derive a class, using the above-mentioned parent and derived class outline:

<?php

    class Calculator
        {
            public $num1;
            public $num2;

            function __construct($param0, $param1)
                {
                    $this->num1 = $param0;
                    $this->num2 = $param1;
                }

            public function add()
                {
                    $sum = $this->num1 + $this->num2;
                    return $sum;
                }
        }

    class ChildCalculator extends Calculator
        {
            public $fixedVal;

            public function square($answer)
                {
                    $finalVal = $answer * $answer + $this->fixedVal;
                    return $finalVal;
                }
        }

        $myChildObj = new ChildCalculator(2, 3);
        $result = $myChildObj->add();
        $myChildObj->fixedVal = 5;
        $endResult = $myChildObj->square($result);
        echo $endResult;

?>

The output is:

    30

The base class calculator has two properties and one method. The derived class has one property and one method. The value that will be assigned to the property of the derived class is considered as the fixed value. The method of the derived class, squares its argument and then adds the value of its property to the square ($answer X $answer). Remember that X in programming is * .

Now, the first line in the last code segment instantiates a derived object from the corresponding derived class. In this code, no object has been instantiated from the base class; that is not necessary as the derived class inherits all the members of the base class. The next statement in the segment calls the inherited add() method of the derived object and the values of the inherited properties are summed. The return value of the inherited add() method is assigned to the fundamental object, $result.

The statement that follows assigns a fixed value of 5 to the only property that belongs to the derived object (class). The statement after, calls the square() method that belongs sorely to the derived object (class), sending the returned value (result) of the inherited method as argument. The square method squares the sum (result) and adds the fixed value; so strictly speaking, this method should not really be given the name, square. The returned value of the square() method is displayed by the echo statement, next.

So a derived class or child class has inherited members that it can use. It can also have its own new members. A derived object is instantiated from the derived class. A base (parent) object is instantiated from the base (parent) class. The instantiated derived class and the instantiated base class are normally independent.

You can still derive a class (and corresponding object) from a derived class to have a grandchild. In this case the former child class becomes the base class and the new child class becomes the derived class. The chain can grow downward.

What is inherited from Base Class?
- The members (attributes and methods) of base class are inherited.
- The constructor function definition and the destructor function definition are inherited from the parent class. Either of these functions can be implicit or explicit.

Overriding
A method can be overridden in the derived class. You use the same name, and the same number of arguments. Read and test the following code, where the add method joins 2 strings, instead of adding 2 numbers:

<?php

    class Calculator
        {
            public $num1;
            public $num2;

            function __construct($param0, $param1)
                {
                    $this->num1 = $param0;
                    $this->num2 = $param1;
                }

            public function add()
                {
                    $sum = $this->num1 + $this->num2;
                    return $sum;
                }
        }

    class ChildCalculator extends Calculator
        {
            public $fixedVal;

            public function add()
                {
                    $sum = $this->num1 . $this->num2;
                    return $sum;
                }

            public function square($answer)
                {
                    $finalVal = $answer . $this->fixedVal;
                    return $finalVal;
                }
        }

        $myChildObj = new ChildCalculator('I am', ' Mr. Bond');
        $result = $myChildObj->add();  
        $myChildObj->fixedVal = ', James Bond.';
        $endResult = $myChildObj->square($result);
        echo $endResult;

?>

The output is:

    I am Mr. Bond, James Bond.

You can override properties by just giving new values to the child object. Replace the last code segment with the following and try again:

        $myChildObj = new ChildCalculator('I am', ' Mr. Bond');
        $myChildObj->num2 = ' Mr. Smith';
        $result = $myChildObj->add();  
        $myChildObj->fixedVal = ', common John Smith.';
        $endResult = $myChildObj->square($result);
        echo $endResult;

The output is:

    I am Mr. Smith, common John Smith.

The final Reserved Word
If you do not want a method to be overridden, just precede the method at the parent class definition, with the word, final. Precede the add() method in the above program with the word, final and re-test the whole script.

In my computer, I did

            final public function add()
                {
                    $sum = $this->num1 + $this->num2;
                    return $sum;
                }

and I had the following fatal error (the program did not run):

    Fatal error: Cannot override final method Calculator::add() in C:Apache24htdocstemp.php on line 36

If you do not want the whole class to be inherited (have a child class), then precede the whole class with the word, final.

Now, remove the word, final from the add() method, and precede the Calculator class with final; then re-test the whole script.

In my computer, I did

    final class Calculator
        {
            public $num1;
            public $num2;
            - - -

and I had the following fatal error (the program did not run):

    Fatal error: Class ChildCalculator may not inherit from final class (Calculator) in C:Apache24htdocstemp.php on line 36

That is it for this part of the series; we take a break here and continue in the next part.

Chrys


Related Links

Basics of PHP with Security Considerations
White Space in PHP
PHP Data Types with Security Considerations
PHP Variables with Security Considerations
PHP Operators with Security Considerations
PHP Control Structures with Security Considerations
PHP String with Security Considerations
PHP Arrays with Security Considerations
PHP Functions with Security Considerations
PHP Return Statement
Exception Handling in PHP
Variable Scope in PHP
Constant in PHP
PHP Classes and Objects
Reference in PHP
PHP Regular Expressions with Security Considerations
Date and Time in PHP with Security Considerations
Files and Directories with Security Considerations in PHP
Writing a PHP Command Line Tool
PHP Core Number Basics and Testing
Validating Input in PHP
PHP Eval Function and Security Risks
PHP Multi-Dimensional Array with Security Consideration
Mathematics Functions for Everybody in PHP
PHP Cheat Sheet and Prevention Explained
More Related Links

Cousins

BACK NEXT

Comments