Introduction:
Welcome to our toturial in PHP Object-Oriented Programming (OOP) – Inheritance. Inheritance is a fundamental concept in OOP, allowing classes to inherit properties and methods from parent classes, promoting code reuse and creating hierarchies of classes. In this lesson, we’ll dive deep into the principles of PHP OOP inheritance, covering everything from syntax to best practices.
In PHP, Object-Oriented Programming (OOP) allows you to create classes that can inherit properties and methods from other classes. This is known as inheritance, and it is a fundamental concept in OOP that promotes code reusability and abstraction.
Here’s an example of inheritance in PHP:
<?php // Parent class class Vehicle { protected $brand; public function __construct($brand) { $this->brand = $brand; } public function start() { echo "Starting the {$this->brand}\n"; } } // Child class inheriting from Vehicle class Car extends Vehicle { private $model; public function __construct($brand, $model) { parent::__construct($brand); $this->model = $model; } public function drive() { echo "Driving the {$this->brand} {$this->model}\n"; } } // Creating instances of the classes $car = new Car("Toyota", "Camry"); // Accessing methods from parent and child classes $car->start(); // Output: Starting the Toyota $car->drive(); // Output: Driving the Toyota Camry ?>
Explanation:
Here’s a step-by-step guide on how to use PHP Object-Oriented Programming (OOP) with Inheritance:
Start by defining a parent class. This class will contain properties and methods that you want to be inherited by child classes.
class Animal { protected $species; public function __construct($species) { $this->species = $species; } public function eat() { echo "The {$this->species} is eating.\n"; } }
class Dog extends Animal { public function bark() { echo "The {$this->species} is barking.\n"; } }
Instantiate objects of both the parent and child classes.
$animal = new Animal("Lion"); $dog = new Dog("Dog");
Access methods from both the parent and child classes using the objects we created.
$animal->eat(); // Output: The Lion is eating. $dog->eat(); // Output: The Dog is eating. $dog->bark(); // Output: The Dog is barking.
we can add additional methods or properties to the child class.
class Dog extends Animal { public function bark() { echo "The {$this->species} is barking.\n"; } public function fetch() { echo "The {$this->species} is fetching.\n"; } }
If we want to utilize the constructor of the parent class in the child class, call it explicitly using parent::__construct().
class Dog extends Animal { public function __construct($species) { parent::__construct($species); } // Other methods here... }
we will create instances of the child class and use their methods.
$dog = new Dog("Golden Retriever"); $dog->eat(); // Output: The Golden Retriever is eating. $dog->bark(); // Output: The Golden Retriever is barking. $dog->fetch(); // Output: The Golden Retriever is fetching.
we’ve successfully used PHP OOP with Inheritance.
This allows for code reuse and promotes a more organized and modular approach to programming.
Complete example about PHP OOP with Inheritance
<!DOCTYPE html> <html> <head> <title>PHP OOP - Inheritance Example</title> </head> <body> <?php // Step 1: Defining the Parent Class class Animal { protected $species; public function __construct($species) { $this->species = $species; } public function eat() { echo "The {$this->species} is eating.<br>"; } } // Step 2: Creating a Child Class class Dog extends Animal { public function bark() { echo "The {$this->species} is barking.<br>"; } } // Step 3: Instantiate Objects $animal = new Animal("Lion"); $dog = new Dog("Dog"); // Step 4: Accessing Inherited Methods echo "<strong>Animal:</strong><br>"; $animal->eat(); // Output: The Lion is eating. echo "<br><strong>Dog:</strong><br>"; $dog->eat(); // Output: The Dog is eating. $dog->bark(); // Output: The Dog is barking. ?> </body> </html>
Explanation:
Step 1:
We define a parent class Animal with a constructor method __construct() and a method eat(). The __construct() method initializes the $species property, and eat() method describes the eating behavior of the animal.
Step 2:
We create a child class Dog that extends the Animal class. The Dog class inherits the properties and methods of the Animal class and adds its own method bark().
Step 3:
We instantiate objects of both the parent ($animal) and child ($dog) classes.
Step 4:
We access the inherited methods using the objects created. We shows that both the parent and child classes have access to the eat() method.
The child class Dog also has access to its own method bark().
This code can be saved as a .php file and run on a server with PHP support. When you open the page in a web browser, we’ll see the output showing inheritance in action, with the animal and dog behaviors displayed accordingly.
<?php class Vehicle { protected $brand; public function __construct($brand) { $this->brand = $brand; } protected function startEngine() { echo "Starting the {$this->brand} engine.\n"; } } class Car extends Vehicle { public function startCar() { // We can access the protected property $brand and protected method startEngine() within the child class. echo "Starting the {$this->brand} car.\n"; $this->startEngine(); } } // Creating an instance of the child class $car = new Car("Toyota"); // Accessing a public method that internally accesses a protected method and property $car->startCar(); // Output: Starting the Toyota car. Starting the Toyota engine. ?>
Explanation:
In this example:
Here’s a step-by-step guide on how to use PHP inheritance with the protected access modifier:
Start by defining a parent class with some protected properties and methods.
class Vehicle { protected $brand; protected function startEngine() { echo "Starting the engine.\n"; } }
class Car extends Vehicle { public function startCar() { // We can access the protected property and method from the parent class here. echo "Starting the car.\n"; $this->startEngine(); } }
How to instantiate objects of both the parent and child classes?
$vehicle = new Vehicle(); $car = new Car();
How to access the protected properties and methods within the child class?
$car->startCar(); // Output: Starting the car. Starting the engine.
Outside the class hierarchy, the protected members are not accessible.
// Trying to access a protected property from outside the class hierarchy will result in an error. // echo $vehicle->brand; // This would cause an error.
Complete Example
Here’s the complete code:
<?php class Vehicle { protected $brand; protected function startEngine() { echo "Starting the engine.\n"; } } class Car extends Vehicle { public function startCar() { echo "Starting the car.\n"; $this->startEngine(); } } // Instantiate objects $vehicle = new Vehicle(); $car = new Car(); // Access protected members $car->startCar(); // Output: Starting the car. Starting the engine. // Trying to access protected members from outside the class hierarchy will result in an error. // echo $vehicle->brand; // This would cause an error. ?>
We’ve successfully used PHP inheritance with the protected access modifier. This helps in encapsulating class internals while allowing child classes to access them for necessary functionality.
In PHP, overriding inherited methods allows child classes to provide their own implementation of a method that is already defined in the parent class. This allows for customization of behavior in child classes while maintaining the inheritance hierarchy.
We will go through a step-by-step example of how to override inherited methods in PHP:
Start by defining a parent class with a method that you want to override in child classes.
class Animal { public function makeSound() { echo "Generic animal sound.\n"; } }
class Dog extends Animal { public function makeSound() { echo "Woof woof!\n"; } }
we will Instantiate objects of both the parent and child classes.
$animal = new Animal(); $dog = new Dog();
Access the methods from both the parent and child classes.
$animal->makeSound(); // Output: Generic animal sound. $dog->makeSound(); // Output: Woof woof!
Here’s the complete code:
<?php class Animal { public function makeSound() { echo "Generic animal sound.\n"; } } class Dog extends Animal { public function makeSound() { echo "Woof woof!\n"; } } // Instantiate objects $animal = new Animal(); $dog = new Dog(); // Access methods $animal->makeSound(); // Output: Generic animal sound. $dog->makeSound(); // Output: Woof woof! ?>
We’ve successfully overridden an inherited method in PHP. This allows child classes to provide their own implementation of methods defined in the parent class, enabling customization and specialization of behavior.
<!DOCTYPE html> <html> <head> <title>PHP - Overriding Inherited Methods</title> </head> <body> <?php // Step 1: Define a Parent Class class Animal { // Method to be overridden public function makeSound() { echo "Generic animal sound.<br>"; } } // Step 2: Create a Child Class class Dog extends Animal { // Override the method from the parent class public function makeSound() { echo "Woof woof!<br>"; } } // Step 3: Instantiate Objects $animal = new Animal(); $dog = new Dog(); // Step 4: Access Methods echo "<strong>Animal:</strong><br>"; $animal->makeSound(); // Output: Generic animal sound. echo "<br><strong>Dog:</strong><br>"; $dog->makeSound(); // Output: Woof woof! ?> </body> </html>
Explanation:
Step 1:
We define a parent class Animal with a method makeSound() that we intend to override in the child class.
Step 2:
We create a child class Dog that extends Animal. Within Dog, we define makeSound() again, effectively overriding the method inherited from Animal.
Step 3:
We instantiate objects of both the parent ($animal) and child ($dog) classes.
Step 4:
We access the overridden methods using the objects created. The makeSound() method behaves differently for the parent (Animal) and child (Dog) objects.
This code can be saved as a .php file and run on a server with PHP support. When you open the page in a web browser, you’ll see the output demonstrating the overridden methods in action, with different sounds being produced for the animal and the dog.
In PHP, the final keyword is used to prevent further inheritance or overriding of classes, methods, or properties. When a class, method, or property is declared as final, it cannot be extended or overridden by any child classes.
final class BaseClass { // Class implementation }
In this example, BaseClass is marked as final, so it cannot be extended by any other class.
class ParentClass { final public function someMethod() { // Method implementation } } class ChildClass extends ParentClass { // Attempting to override a final method will result in an error. // public function someMethod() { // // Method implementation // } }
Here, someMethod() in ParentClass is marked as final, so it cannot be overridden by any child class.
class MyClass { final public $someProperty = 'value'; }
In this example, $someProperty is marked as final, so it cannot be overridden or re-declared in any child class.
Important Notes:
The final keyword can be used in conjunction with the abstract keyword. However, it cannot be used with the abstract keyword on the same element (e.g., a class cannot be both final and abstract).
Attempting to extend a final class, override a final method, or re-declare a final property will result in a fatal error.
Using final helps in enforcing certain aspects of your class design, particularly when you want to prevent further extension or modification of specific elements.
<?php class BaseClass { final public function someMethod() { echo "This method cannot be overridden.\n"; } } class ChildClass extends BaseClass { // Attempting to override a final method will result in an error. // public function someMethod() { // echo "This method cannot be overridden.\n"; // } } // Instantiating objects $base = new BaseClass(); $child = new ChildClass(); // Accessing the method $base->someMethod(); // Output: This method cannot be overridden. ?>
In this example, attempting to override the someMethod() in ChildClass will result in a fatal error due to its final declaration in BaseClass.
Here is a step-by-step guide along with a complete code example showing the use of the final keyword in PHP:
Start by defining a parent class with a final method:
<?php class ParentClass { final public function finalMethod() { echo "This method is final and cannot be overridden.\n"; } } ?>
Attempt to override the final method in a child class:
<?php class ChildClass extends ParentClass { // Attempting to override a final method will result in an error. // public function finalMethod() { // echo "Trying to override the final method.\n"; // } } ?>
Instantiate objects of both the parent and child classes and access the final method:
<?php // Instantiate objects $parent = new ParentClass(); $child = new ChildClass(); // Access the final method $parent->finalMethod(); // Output: This method is final and cannot be overridden. ?>
Here’s the complete code example:
<?php // Step 1: Define a Parent Class with a Final Method class ParentClass { final public function finalMethod() { echo "This method is final and cannot be overridden.\n"; } } // Step 2: Attempt to Override the Final Method class ChildClass extends ParentClass { // Attempting to override a final method will result in an error. // public function finalMethod() { // echo "Trying to override the final method.\n"; // } } // Step 3: Instantiate Objects and Access Methods // Instantiate objects $parent = new ParentClass(); $child = new ChildClass(); // Access the final method $parent->finalMethod(); // Output: This method is final and cannot be overridden. ?>
In this example, attempting to override the finalMethod() in ChildClass is commented out, as it will result in a fatal error due to its final declaration in ParentClass.
complete code example in web page
Here is the complete PHP code example embedded in a web page, demonstrating the use of the final keyword:
<!DOCTYPE html> <html> <head> <title>PHP - The final Keyword Example</title> </head> <body> <?php // Step 1: Define a Parent Class with a Final Method class ParentClass { final public function finalMethod() { echo "This method is final and cannot be overridden.<br>"; } } // Step 2: Attempt to Override the Final Method class ChildClass extends ParentClass { // Attempting to override a final method will result in an error. // public function finalMethod() { // echo "Trying to override the final method.<br>"; // } } // Step 3: Instantiate Objects and Access Methods // Instantiate objects $parent = new ParentClass(); $child = new ChildClass(); // Access the final method $parent->finalMethod(); // Output: This method is final and cannot be overridden. ?> </body> </html>
This code can be saved as a .php file and run on a server with PHP support. When you open the page in a web browser, you’ll see the output demonstrating the use of the final keyword. The attempt to override the final method in ChildClass is commented out to avoid a fatal error.
php-oop-inheritance/
│
├── classes/
│ ├── Vehicle.php
│ └── Car.php
│
└── index.php
we will Create a file named Vehicle.php inside the classes/ directory:
<?php class Vehicle { protected $brand; public function __construct($brand) { $this->brand = $brand; } public function start() { return "Starting the $this->brand.\n"; } } ?>
Create another file named Car.php inside the classes/ directory:
<?php require_once('Vehicle.php'); class Car extends Vehicle { private $model; public function __construct($brand, $model) { parent::__construct($brand); $this->model = $model; } public function drive() { return "Driving the $this->brand $this->model.\n"; } } ?>
we will Create an index.php file in the project root directory to use the classes:
<!DOCTYPE html> <html> <head> <title>PHP OOP - Inheritance</title> </head> <body> <?php // Autoload classes spl_autoload_register(function ($class_name) { include 'classes/' . $class_name . '.php'; }); // Create instances $car = new Car("Toyota", "Camry"); // Access inherited methods echo "<p>" . $car->start() . "</p>"; // Output: Starting the Toyota. echo "<p>" . $car->drive() . "</p>"; // Output: Driving the Toyota Camry. ?> </body> </html>
Explanation:
Step 1: We define the Vehicle class with a protected property $brand and a method start().
Step 2: We define the Car class that extends the Vehicle class. It adds its own property $model and method drive(). We include the Vehicle.php file to ensure the parent class is available.
Step 3: We autoload the classes using spl_autoload_register(). Then we create an instance of Car and access its inherited methods to start and drive the car.
Place all files in the project structure.
Make sure your web server is running and configured to serve PHP files.
Open index.php in your web browser.
You should see the output showing inheritance in action, with the car being started and driven.
let’s create another PHP project showing inheritance, but this time let’s create a more abstract example. We’ll have a base class Shape representing geometric shapes, and two child classes Rectangle and Circle representing specific types of shapes. Each shape will have its own properties and methods.
php-shape-inheritance/
│
├── classes/
│ ├── Shape.php
│ ├── Rectangle.php
│ └── Circle.php
│
└── index.php
Create a file named Shape.php inside the classes/ directory:
<?php class Shape { protected $color; public function __construct($color) { $this->color = $color; } public function getColor() { return $this->color; } public function getArea() { // Abstract method to be implemented by child classes } } ?>
Create a file named Rectangle.php inside the classes/ directory:
<?php require_once('Shape.php'); class Rectangle extends Shape { protected $width; protected $height; public function __construct($color, $width, $height) { parent::__construct($color); $this->width = $width; $this->height = $height; } public function getArea() { return $this->width * $this->height; } } ?>
we will Create a file named Circle.php inside the classes/ directory:
<?php require_once('Shape.php'); class Circle extends Shape { protected $radius; public function __construct($color, $radius) { parent::__construct($color); $this->radius = $radius; } public function getArea() { return pi() * pow($this->radius, 2); } } ?>
we will Create an index.php file in the project root directory to use the classes:
<!DOCTYPE html> <html> <head> <title>PHP - Shape Inheritance</title> </head> <body> <?php // Autoload classes spl_autoload_register(function ($class_name) { include 'classes/' . $class_name . '.php'; }); // Create instances $rectangle = new Rectangle("blue", 5, 4); $circle = new Circle("red", 3); // Access inherited methods echo "<p>The area of the rectangle is: " . $rectangle->getArea() . "</p>"; // Output: The area of the rectangle is: 20 echo "<p>The area of the circle is: " . $circle->getArea() . "</p>"; // Output: The area of the circle is: 28.274333882308 ?> </body> </html>
Explanation:
Step 1: We define the Shape class with a protected property $color and a method getColor(). It also has an abstract method getArea() which will be implemented by child classes.
Step 2: We define the Rectangle class that extends the Shape class. It adds its own properties $width and $height and implements the getArea() method to calculate the area of a rectangle.
Step 3: We define the Circle class that extends the Shape class. It adds its own property $radius and implements the getArea() method to calculate the area of a circle.
Step 4: In index.php, we autoload the classes using spl_autoload_register(), create instances of Rectangle and Circle, and access their inherited getArea() methods to calculate their respective areas.
Place all files in the project structure.
Make sure your web server is running and configured to serve PHP files.
Open index.php in your web browser.
You should see the output displaying the calculated areas of a rectangle and a circle.
we will create a multiple-choice quiz about PHP OOP – Inheritance:
A) A mechanism to allow a class to inherit properties and methods from another class.
B) A way to create new classes.
C) A method to access private properties.
D) A function to override parent class methods.
A) extends
B) inherit
C) include
D) inheritFrom
A) public
B) private
C) protected
D) internal
A) It will result in a warning.
B) It will result in a fatal error.
C) It will execute both the parent and child methods.
D) It will override the parent method.
A) Child classes can override parent class methods.
B) It promotes code reuse.
C) It increases coupling between classes.
D) It allows for specialization of behavior.
A) final
B) end
C) finish
D) close
A) __construct()
B) __init()
C) start()
D) create()
A) It calls a method from the parent class.
B) It creates a new instance of the parent class.
C) It deletes the parent class.
D) It checks if the current class is a child class.
A) Abstract classes cannot have abstract methods.
B) Abstract classes cannot be inherited.
C) Abstract methods must be implemented in child classes.
D) Abstract classes cannot have properties.
A) To manually load classes one by one.
B) To define autoloading rules for classes.
C) To unload classes after use.
D) To prevent inheritance.
A) __tostring()
B) __stringify()
C) __convert()
D) __string()
A) Use the final keyword before the class declaration.
B) Use the private keyword before the class declaration.
C) Use the protected keyword before the class declaration.
D) Use the static keyword before the class declaration.
A) It increases code complexity.
B) It allows for tighter coupling between classes.
C) It promotes code reusability.
D) It eliminates the need for encapsulation.
A) When classes have unrelated functionality.
B) When there is no need for code reuse.
C) When classes share common behavior.
D) When you want to create new classes from scratch.
A) super
B) base
C) parent
D) this
Explanation:
A) A mechanism to allow a class to inherit properties and methods from another class. – Inheritance allows a class to inherit properties and methods from another class, promoting code reuse and creating a hierarchy of classes.
A) extends – The extends keyword is used in PHP to indicate inheritance.
C) protected – The protected access modifier in PHP allows a property or method to be accessible only within the class itself and its child classes.
B) It will result in a fatal error. – Attempting to override a final method in a child class will result in a fatal error.
C) It increases coupling between classes. – Inheritance can increase coupling between classes, making them more dependent on each other.
A) final – The final keyword is used to mark a method as final in PHP, preventing it from being overridden in child classes.
A) __construct() – The __construct() method is automatically called in a child class when it is instantiated.
A) It calls a method from the parent class. – The parent:: keyword in PHP is used to call a method from the parent class within a child class.
C) Abstract methods must be implemented in child classes. – Abstract classes in PHP can have abstract methods, which must be implemented in child classes.
B) To define autoloading rules for classes. – spl_autoload_register() in PHP is used to define autoloading rules for classes, allowing them to be loaded automatically when needed.
A) __tostring() – The __tostring() method is called when an object is being converted to a string in PHP.
A) Use the final keyword before the class declaration. – To prevent a class from being inherited in PHP, you can use the final keyword before the class declaration.
C) It promotes code reusability. – Inheritance in PHP OOP promotes code reusability by allowing classes to inherit properties and methods from other classes.
C) When classes share common behavior. – It is appropriate to use inheritance in PHP OOP when classes share common behavior and can benefit from code reuse.
C) parent – The parent keyword is used to access the parent class constructor within a child class constructor in PHP.