Home >Backend Development >PHP Tutorial >How to override functions in PHP?
Function overriding in PHP involves overriding a method of the same name in the parent class for code reuse, polymorphism and maintenance. Syntax: class Subclass extends Superclass { public function overridenMethod() { // Custom implementation } }. The overridden function signature must be consistent with that in the parent class; it is recommended to add the @override annotation to improve readability; the parent:: syntax allows access to the original implementation of the parent class method.
How to override functions in PHP
PHP allows you to override functions by overriding the method of the same name in the parent class. This is very useful in object-oriented programming, enabling code reuse, polymorphism, and code maintenance.
Syntax
class Subclass extends Superclass { public function overridenMethod() { // 自定义实现 } }
Practice
Suppose we have a Animal
class, containing a speak()
method, this method prints a general message. Then create a Dog
subclass and override the speak()
method to print out a more specific dog barking sound.
class Animal { public function speak() { echo "Generic animal sound."; } } class Dog extends Animal { public function speak() { echo "Woof!"; } } $animal = new Animal(); $animal->speak(); // 输出: "Generic animal sound." $dog = new Dog(); $dog->speak(); // 输出: "Woof!"
Note:
@override
, it may improve the readability and maintainability of the code. The parent::
syntax can be used to access the original implementation of a parent class in an overridden method. The above is the detailed content of How to override functions in PHP?. For more information, please follow other related articles on the PHP Chinese website!