Home Backend Development PHP Tutorial Detailed explanation of new method instances for PHP object-oriented overloading

Detailed explanation of new method instances for PHP object-oriented overloading

Jul 08, 2017 am 11:32 AM
php method

When learning PHP, you will find that methods in PHP cannot be overloaded. The so-called method overloading means defining the same method name by " The number of parameters or the type of parameters are different to access different methods with the same method name.

12. Overload new methods
When learning PHP, you will find that methods in PHP cannot be overloaded. The so-called method overloading is
Define the same method name, and access our different methods with the same
name through different "number of parameters" or different "type of parameters". However, because PHP is a weakly typed language, it can receive different types of data in the parameters of the method. And because the PHP method can receive an indefinite number of parameters, it can be called by passing a different number 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 have 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 "Person" human being
has a "speak" method, and all those that 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 talks about the
attributes
in the "Person" class, and the "Student" class extends the "Person" class and extends several new attributes. If If you use the inherited "say()" speaking method, you can only speak those attributes inherited from the
"Person" class, then the newly extended attributes use the inherited "say()" The method cannot be named, so some people have asked, if I define a new method in the "Student" subclass for speaking, wouldn't it be enough to just name 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 "speaking" method may not have a chance to be used, and you cannot delete it if it is inherited.
At this time we will use coverage.
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 can be defined. The method is overridden.
Code snippet


The code is as follows:

<?php 
//定义一个“人”类做为父类 
class Person{ 
//下面是人的成员属性 
var $name; //人的名子 
var $sex; //人的性别 
var $age; //人的年龄 
//定义一个
构造方法
参数为属性姓名$name、性别$sex和年龄$age进行赋值 
function construct($name, $sex, $age){ 
$this->name=$name; 
$this->sex=$sex; 
$this->age=$age; 
} 
//这个人可以说话的方法, 说出自己的属性 
function say() { 
echo "我的名子叫:".$this->name." 性别:".$this->sex." 我的年龄是:".$this->age."<br>"; 
} 
} 
class Student 
extends
 Person 
{ 
var $school; //学生所在学校的属性 
//这个学生学习的方法 
function study() { 
echo "我的名子叫:".$this->name." 我正在”.$this->school.”学习<br>"; 
} 
//这个学性可以说话的方法, 说出自己所有的属性,覆盖了父类的同名方法 
function say() { 
echo "我的名子叫:".$this->name." 性别:".$this->sex." 我的年龄是:".$this->age."我在 
".$this->school."上学.<br>"; 
} 
} 
?>
Copy after login

In the above example, we overwrote the "say()" inherited from the parent class in the "Student" subclass Method, by covering
we realize the extension of "method".

However, although doing this solves the problem we mentioned above, in actual development, a method cannot

consist of one code or several codes, such as "say(" in the "Person" class )" method has 100 lines of code in it. If

we want to overwrite this method and retain the original functions plus a little bit more, we have to rewrite the original 100 lines of code

once and add The several lines of code extended above are pretty good, but in some cases, the methods in the parent class cannot see the original code
. How do you rewrite the original code at this time? We also have a solution, that is, in the method of the subclass, we can
call the overridden method in the parent class, that is, take the original functions of the overridden method and add some of our own
Function, you can use two methods to call the overridden method of the parent class in the method of the subclass:
One is to use the "class name::" of the parent class to call the overridden method of the parent class;
One is to use "parent::" method to call the overridden method in the parent class;
Code snippet


The code is as follows:

class Student extends Person{ 
var $school; //学生所在学校的属性 
//这个学生学习的方法 
function study() { 
echo "我的名子叫:".$this->name." 我正在”.$this->school.”学习<br>"; 
} 
//这个学性可以说话的方法, 说出自己所有的属性,覆盖了父类的同名方法 
function say() { 
//使用父类的“类名::“来调用父类中被覆盖的方法; 
// Person::say(); 
//或者使用“parent::”的方试来调用父类中被覆盖的方法; 
parent::say(); 
//加上一点自己的功能 
echo “我的年龄是:".$this->age."我在".$this->school."上学.<br>"; 
} 
}
Copy after login


Now you can access the overridden methods in the parent class in two ways. Which method should we choose best? Users may

会发现自己写的代码访问了父类的变量和函数。如果子类非常精炼或者父类非常专业化的时
候尤其是这样。不要用代码中父类文字上的名字,应该用特殊的名字parent,它指的就是子
类在extends 声明中所指的父类的名字。这样做可以避免在多个地方使用父类的名字。如果继
承树在实现的过程中要修改,只要简单地修改类中extends 声明的部分。
同样,构造方法在子类中如果没有声明的话,也可以使用父类中的构造方法,如果子类
中重新定义了一个构造方法也会覆盖掉父类中的构造方法,如果想使用新的构造方法为所有
属性赋值也可以用同样的方式。
代码片段

代码如下:

class Student extends Person{ 
var $school; //学生所在学校的属性 
function construct($name, $sex, $age, $school){ 
//使用父类中的方法为原有的属性赋值 
parent::construct($name, $sex, $age); 
$this->school=$school; 
} 
//这个学生学习的方法 
function study() { 
echo "我的名子叫:".$this->name." 我正在”.$this->school.”学习<br>"; 
} 
//这个人可以说话的方法, 说出自己的属性 
function say() { 
parent::say(); 
//加上一点自己的功能 
echo “我的年龄是:".$this->age."我在".$this->school."上学.<br>";
Copy after login


The above is the detailed content of Detailed explanation of new method instances for PHP object-oriented overloading. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles