happy cat image

everdevel

coding

login
NotificationX
  • Currently, only notices of comments are displayed.
  • no comment or please login

Class inheritance

To use the features of other classes, use inheritance.
Use the extends keyword.

Class inheritance method

class child class name extends parent class

Then, following the previous course ... The previous example becomes a child class and we will create a parent class and inherit it. Let's say Google has created a state-of-the-art AI driving system and make it simple with classes first.

<?php
    class GoogleCar
    {
        public function stateOfTheArtAIDrivingSystem()
        {
            return "Google AI Driving";
        }
    }
?>

I created a class called GoogleCar above.
Inheriting this, we will create an instance of the Car class and call the stateOfTheArtAIDrivingSystem() method in the GoogleCar class.

<?php

    class GoogleCar
    {
        public function stateOfTheArtAIDrivingSystem()
        {
            return "Google AI Driving";
        }
    }

    class Car extends GoogleCar
    {
        public $wheels;
        public $doors = 4;
        protected $color = 4;
        private $size;
        private $company;

        public function run()
        {
            return "The car is running.";
        }

        protected function stop()
        {
            return "car stops.";
        }

        protected function turn()
        {
            return "turnning car";
        }
    }
    $honda = new Car;
    echo $honda->stateOfTheArtAIDrivingSystem();
?>

Result of the code above

As an implicit promise between programmers, you declare one class in one file.
In the case above, we have declared two classes in one place for the sake of example. ^^;
This time, I'll use the properties in the parent class on an instance of the child class.

<?php

    class GoogleCar
    {
        public $parentCompany = 'google';

        public function stateOfTheArtAIDrivingSystem()
        {
            return "Google AI Driving";
        }
    }

    class Car extends GoogleCar
    {
        public $wheels;
        public $doors = 4;
        protected $color = 4;
        private $size;
        private $company;

        public function run()
        {
            return "The car is running.";
        }

        protected function stop()
        {
            return "car stops.";
        }

        protected function turn()
        {
            return "turnning car";
        }
    }
    $honda = new Car;
    echo $honda->parentCompany.'<br>';
    echo $honda->stateOfTheArtAIDrivingSystem();
?>

Result of the code above

If the accessors of the properties and methods of class GoogleCar were not public, the code above would not work. Now let's test the access restriction.


Thank you for visiting. If you have any inquiry or explanation of mistakes, please use the comments below.


    
    

Back to the course

ALL COMMENTS 0

Sort by