Function overriding is a powerful feature in object-oriented programming that allows a subclass to provide a different implementation of a function that is already defined in its superclass. PHP, being an object-oriented programming language, offers a simple way to achieve function overriding. In this blog post, we will learn how to override functions in PHP with the help of a step-by-step example.
Step 1: Define the base class
First, let’s create a base class (also known as the superclass) with a function that we want to override in a subclass (derived class). In this example, we will create a base class called Animal with a function speak().
class Animal { public function speak() { echo "The animal makes a sound"; } }
Step 2: Create a subclass
Now, let’s create a subclass (derived class) called Dog that inherits from the base class Animal. To achieve inheritance, we use the extends keyword.
class Dog extends Animal { }
Step 3: Override the function in the subclass
To override the speak() function, we need to redefine it in the subclass. This new implementation will replace the original function when called on objects of the subclass.
class Dog extends Animal { public function speak() { echo "The dog barks"; } }
Step 4: Test the overridden function
Finally, let’s create objects for both the base class and the subclass and call the speak() function on them. The output should demonstrate that the function has been successfully overridden in the Dog subclass.
$animal = new Animal(); $animal->speak(); // Output: The animal makes a sound $dog = new Dog(); $dog->speak(); // Output: The dog barks
As we can see from the output, the speak() function has been overridden in the Dog subclass, and the new implementation has replaced the original one.
Conclusion
Function overriding in PHP is a simple yet powerful feature that allows subclasses to provide their own implementation of a function defined in their superclass. This enables programmers to create more flexible and reusable code, as well as adhere to object-oriented programming principles.