search
HomeBackend DevelopmentPHP TutorialPHP object-oriented programming - in-depth understanding of method overloading and method coverage (polymorphism), polymorphism coverage_PHP tutorial

PHP object-oriented programming - in-depth understanding of method overloading and method coverage (polymorphism), polymorphism coverage

What is polymorphism?

Polymorphism literally means "multiple states". In object-oriented languages, multiple different implementations of an interface are called polymorphism. Quoting Charlie Calverts' description of polymorphism - Polymorphism is a technique that allows you to set a parent object to be equal to one or more of its child objects. After assignment, the parent object can be assigned to its child objects based on the current value. features operate in different ways (from "Insider Delphi 4 Programming Technology"). To put it simply, it is one sentence: It is allowed to assign a pointer of a subclass type to a pointer of a parent class type (yes, this passage comes from Baidu Encyclopedia). So what is the role of polymorphism, and what is its actual development value? In actual application development, the main purpose of using object-oriented polymorphism is that different subclass objects can be treated as one parent class, and the differences between different subclass objects can be shielded and universal objects can be written. Code, making general programming to adapt to changing needs.

The following are two implementations of polymorphism in PHP

Method overload (overload)

Overloading is an implementation of class polymorphism. Function overloading means that an identifier is used as multiple function names and can be passed through the function's number of parameters or parameter type Distinguish these functions with the same name so that there is no confusion when calling. That is, when called, although the method names are the same, the corresponding functions can be automatically called according to different parameters.

class A{
	public function test(){
		echo "test1";
	}
	public function test($a){
		echo "test2";
	}
}
$a=new A();
$a->test();
$a->test($a);

If php directly supports method overloading. Then after the above example is executed, different values ​​will be returned if parameters are passed and if no parameters are passed. However, php does not directly support overloading , which means that if you define it directly as above, an error will be reported. What error will be reported? The following error will be reported.

This means that function A cannot be defined repeatedly, and the number of lines reporting the error is exactly the following line.

public function test($a){

So php does not directly support reloading. The co-author has been saying for a long time that php does not support it. . Don't worry, what I said is that it is not directly supported, so we can let php support it indirectly. At this time, a function will be used to support overloading. It's __call(). The __call() method must take two parameters. The first one contains the name of the method being called, while the second parameter contains the array of parameters passed to the method. Functions similar to function overloading can be achieved through this method. Look at the code below.

public function __call($method,$p<span>)
{
    if($method=="display"<span>){
        if(is_object($p[0<span>])){
            $this->displayObject($p[0<span>]);
        }else if(is_array($p[0<span>])){
            $this->displayArray($p[0<span>]);
        }else<span>{
            $this->displayScalar($p[0<span>]);
        }
    }
}<br />
//下面是对上面定义的调用
$ov=new<span> overload;
$ov->display(array(1,2,3<span>));
$ov->display('cat');</span></span></span></span></span></span></span></span></span></span>

When defining a method, you can see that there are three branches. If an object is passed to the display() method, the displayObject() method is called; if an array is passed, displayArray() is called; pass If it contains other content, the displayScalar() method is called. . . You can see that when calling below, the first one is to pass an array, then displayArray() is called. The second one passed in is neither an object nor an array, it belongs to other content, and the displayScalar() method is called. So in this way, the __call() method is used to implement method overloading similar to other languages.

Method override

The so-called overwriting is essentially rewriting. That is, when a subclass inherits some methods from the parent class, and the subclass defines the same method internally, the newly defined method will override the inherited method from the parent class, and the subclass can only call its internally defined methods. method.

has the following requirements:

1. When a parent class and a subclass have a method with exactly the same parameters and names, then the subclass method will override the parent class method.

2. When implementing method coverage, the access modifiers can be different, but the access scope of the subclass must be greater than or equal to the access scope of the parent class.

3. The parameters are required to be the same as the name. It is not required that the subclass has the same name as the parent class.

The following is an explanation of these points:

The first point is that the parameters must be consistent to achieve method coverage. When the number of parameters is inconsistent, an error will be reported (this involves the overloading of the above-mentioned methods). When the method names are inconsistent, they will not be overwritten, only the newly defined methods of the subclass. ;

The second point is that this is the design rule of languages ​​​​such as php. What I understand is that it is easier to access things at a higher level. If you want to access things at a lower level, you must have higher permissions.

Look at the code:

class<span> people{
    protected function<span> sing(){
        echo "人唱歌"<span>;
    }
} 
class woman extends<span> people{
    public function<span> sing(){
        echo "女人唱歌"<span>;
    }
}
$woman1=new<span> woman();
$woman1->sing();</span></span></span></span></span></span></span>

This is a normal way to output "women singing". But when the sing() method in woman is changed to proctcted and the parent element is changed to public(), that is, after the access permission of the parent class is set to be greater than that of the subclass, the following error will be reported.

The third point is that the parameters are required to be the same as their names. Specifically, the number of parameters is required to be the same as the parent class, not the parameters The name is consistent. That is, the name of the parameters passed can be arbitrary, as long as the number passed is the same.

The above introduces two implementations of polymorphism in the PHP language.

Well, that’s pretty much it. .

http://www.bkjia.com/PHPjc/1083560.html

truehttp: //www.bkjia.com/PHPjc/1083560.htmlTechArticlePHP object-oriented programming - an in-depth understanding of method overloading and method coverage (polymorphism), what is polymorphic coverage? Polymorphic? Polymorphism literally means multiple states. In person...
Statement
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
Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Give an example of how to store a user's name in a PHP session.Give an example of how to store a user's name in a PHP session.Apr 26, 2025 am 12:03 AM

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools