Home >Backend Development >PHP Tutorial >PHP object-oriented guide (8) Overloading new methods_PHP tutorial
12. Overload new methods
When learning PHP, you will find that methods in PHP cannot be overloaded. The so-called method overloading means
defining the same method Name, through different "number of parameters" or different "type of parameters", to access different methods of our same method
name. However, because PHP is a weakly typed language, it can receive different types of data in the parameters of the method itself. And because the PHP method can receive an indefinite number of parameters, it can be called by passing different numbers of parameters.
Different methods with different method names are also not valid. So there is no method overloading in PHP. It cannot be overloaded, which means that methods with the same method name cannot be defined in
your project. In addition, because PHP does not have the concept of name subspace, methods with the same name cannot be defined on the same page
and included pages, nor can they be defined with the same name as the method provided by PHP, of course
Methods with the same name cannot be defined in the same class.
What do we mean by overloading new methods here? In fact, what we call overloading a new method is that the subclass
overrides the existing method of the parent class, so why do we do this? Can’t the methods of the parent class be inherited and used directly? But
there are some situations that we must cover. For example, in the example we mentioned earlier, the human being "Person"
has a "speak" method, and all those who inherit the "Person" class All subclasses can "speak". Our "Student"
class is a subclass of the "Person" class, so instances of "Student" can "speak", but humans "speak
words" The method states the attributes in the "Person" class, and the "Student" class extends the "Person" class and several new attributes. If you use the inherited "say ()" speaking method, you can only speak those attributes inherited from the
"Person" class, but the newly extended attributes cannot be spoken using the inherited "say()"
method. Yes, some people asked, if I define a new method in the "Student" subclass for
to speak, wouldn't it be enough to tell all the attributes in the subclass? Be sure not to do this. From an abstract point of view, a "student" cannot have two ways of "speaking". Even if you define two different speaking methods, you can achieve what you want
Function, the inherited "talk" method may not be used anymore, and you cannot delete it even if it is inherited.
At this time we will use overlay.
Although methods with the same name cannot be defined in PHP, in the two classes with a parent-child relationship, we can define methods with the same name as the parent class in the subclass
, so that the methods inherited from the parent class The method is overridden.
Code snippet
Copy code