Inheritance

5th Feb 19
elephants

I am going through the Object Orientated Programming in PHP 7.  This blog covers Inheritance, 

Inheritance

Inheritance allows a class to use properties and methods of another class. It means that a class can be defined using another class as a foundation.  So one class can inherit fields and methods from another class.  A class that inherits from other class is called a sub class and the class it inherits from is call the base class.

Example I was given was a vehicle company with range of vehicles.  The base class is vehicle which sets the number of wheels, getSpeed, setSpeed, colour.  All the methods and properties that would apply across all of the vehicles

	class Vehicle{
		private $noOfWheels;
		private $color;
		private $fuel;
		private $speed;
		
		public function getNoOfWheels(){
			return $this->noOfWheels;
		}
		
		public function setNoOfWheels($wheels){
			$this->noOfWheels = $wheels;
			echo "No of Wheels are ". $this->noOfWheels."</br>";
		}
		
		public function getColor(){
			return $this->color;
		}
		
		public function setColor($color){
			$this->color = $color;
			echo "Color is ". $this->color."</br>";
		}
		
		public function getFuel(){
			return $this->fuel;
		}
		
		public function setFuel($fuel){
			$this->fuel = $fuel;
			echo "Fuel is ". $this->fuel."</br>";
		}
		
		public function getSpeed(){
			return $this->speed;
		}
		
		public function setSpeed($speed){
			$this->speed = $speed;
			echo "Speed is ". $this->speed."</br>";
		}
		
		public function start(){
			echo "vehicle is starting...</br>";
		}
		
		public function accelerate(){
			echo "vehicle is accelerating...</br>";
		}
		
		public function brake(){
			echo "vehicle is Stoping...</br>";
		}
	
	}

You then have the passenger vehicle that is the sub class of vehicle class.  It has an additional property passengerSeats with a getter and setter method:

	class PassengerVehicle extends Vehicle{
		private $passengerSeats;
		
		public function getPassengerSeats(){
			return $this->passengerSeats;
		}
		public function setPassengerSeats($seats){
			return $this->passengerSeats = $seats;
			echo "No of seats are ". $this->passengerSeats."</br>";
		}
	}

The PassengerVechicle class is a base class for two classes bike and car:

	class Bike extends PassengerVehicle{
		private $saddleHeight;
		public function getSaddleHeight(){
			return $this->saddleHeight ;
		}
		public function setSaddleHeight($saddleHeight){
			return $this->saddleHeight  = $saddleHeight;
		}
	}
		
	class Car extends PassengerVehicle{
		private $noOfDoors;
		public function getNoOfDoors(){
			return $this->noOfDoors ;
		}
		public function setNoOfDoors($noOfDoors){
			return $this->noOfDoors  = $noOfDoors;
			echo "No of Doors are ". $this->noOfDoors."</br>";
		}
	}

In this way methods and properties are passed from parent class to child class.

I have recently completed my apprenticeship.  I am currently building the API to a React JS site using Firebase.