PHP面向对象编程深入理解方法重载与方法覆盖(多态),多态覆盖
PHP面向对象编程——深入理解方法重载与方法覆盖(多态),多态覆盖
什么是多态?
多态(Polymorphism)按字面的意思就是“多种状态”。在面向对象语言中,接口的多种不同的实现方式即为多态。引用Charlie Calverts对多态的描述——多态性是允许你将父对象设置成为和一个或更多的他的子对象相等的技术,赋值之后,父对象就可以根据当前赋值给它的子对象的特性以不同的方式运作(摘自“Delphi4编程技术内幕”)。简单的说,就是一句话:允许将子类类型的指针赋值给父类类型的指针(没错这段话来自百度百科)。那么多态的作用是什么,它有什么实际开发价值呢?在实际的应用开发中,采用面向对象中的多态主要在于可以将不同的子类对象都当作一个父类来处理,并且可以屏蔽不同子类对象之间所存在的差异,写出通用的代码,做出通用的编程,以适应需求的不断变化。
下面就是PHP中多态的两个实现
方法重载(overload)
重载是类的多态的一种实现。函数重载指一个标识符被用作多个函数名,且能够通过函数的参数个数或参数类型将这些同名的函数区分开来,调用不发生混淆。即当调用的时候,虽然方法名字相同,但根据参数的不同可以自动调用相应的函数。
class A{ public function test(){ echo "test1"; } public function test($a){ echo "test2"; } } $a=new A(); $a->test(); $a->test($a);
假如php直接支持方法重载的话。那么上面的例子执行后传参和不传参就会返回不同的值。然而php并不直接支持重载,这就意味着你如果直接按上面这样定义的话,就会报错的。会报什么错呢?会报如下的错误。
这意思就是不能重复定义A函数,报错的行数也正是下面这行。
public function test($a){
所以说php是并不直接支持重载的。合着说了这么半天php并不支持。。别急,我说的是并不直接支持,所以说是我们可以让php间接支持。这时候就要用到一个函数来支持重载了。就是__call()。__call()方法必须带有两个参数。第一个包含了被调用的方法名称,而第二个参数包含了传递给该方法的参数数组。可以通过这个方法实现类似于函数重载的功能。看下面的代码。
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>
定义方法的时候,可以看到有三个分支,如果一个对象传递给display()方法,就调用的是displayObject()方法;如果传递的是一个数组,调用displayArray();传递的是其他的内容的话,则调用的是displayScalar()方法。。。可以看到下面调用时,第一个是传递了一个数组,则调用displayArray()。第二个传入的不是对象也不是数组,则属于其他内容,调用的是displayScalar()方法。所以这样子就用__call()方法实现了类似于其他语言的方法重载。
方法覆盖(override)
所谓覆盖,从本质上来说就是重写。就是当子类继承父类的一些方法后,子类又在其内部定义了相同的方法,则这个新定义的方法会覆盖继承而来的父类的方法,子类只能调用其内部定义的方法。
有以下几点要求:
1.当一个父类和子类有一个方法,参数和名字完全一致,那么子类方法会覆盖父类的方法。
2.在实行方法覆盖的时候,访问修饰符可以是不一样的,但是子类的访问范围必须大于等于父类的访问范围。
3.要求参数和名字一样。并不是要求子类,父类名称相同。
下面是对这几点的解释:
第一点,必须参数一致,才会实现方法覆盖。当参数个数不一致,则会报错(这就牵扯到上面说所得方法重载)。当方法名字不一致,就不会覆盖,只是子类新定义的方法。;
第二点,这是php这些语言设计时的规定吧。我是这么理解的是访问高一层的东西比较容易,如果再去访问底层的东西权限肯定要高一些。
看代码:
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>
这样很正常的可以输出“女人唱歌”。但当把woman里的sing()方法改为proctcted,父元素改成public()时,即将父类的访问权限设置的大于子类后,就会报下面的错误。
第三点,是要求参数和名字一样,具体就是要求参数的个数与父类相同,而并不是参数名称一致。即传递的参数名字可以为任意,只要保证传递的个数相同即可。
上面简介了PHP语言中多态的两个实现。
嗯,差不多就是这样。。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Introduction In today's rapidly evolving digital world, it is crucial to build robust, flexible and maintainable WEB applications. The PHPmvc architecture provides an ideal solution to achieve this goal. MVC (Model-View-Controller) is a widely used design pattern that separates various aspects of an application into independent components. The foundation of MVC architecture The core principle of MVC architecture is separation of concerns: Model: encapsulates the data and business logic of the application. View: Responsible for presenting data and handling user interaction. Controller: Coordinates the interaction between models and views, manages user requests and business logic. PHPMVC Architecture The phpMVC architecture follows the traditional MVC pattern, but also introduces language-specific features. The following is PHPMVC

SOLID principles are a set of guiding principles in object-oriented programming design patterns that aim to improve the quality and maintainability of software design. Proposed by Robert C. Martin, SOLID principles include: Single Responsibility Principle (SRP): A class should be responsible for only one task, and this task should be encapsulated in the class. This can improve the maintainability and reusability of the class. classUser{private$id;private$name;private$email;publicfunction__construct($id,$nam

In high-concurrency scenarios of object-oriented programming, functions are widely used in the Go language: Functions as methods: Functions can be attached to structures to implement object-oriented programming, conveniently operating structure data and providing specific functions. Functions as concurrent execution bodies: Functions can be used as goroutine execution bodies to implement concurrent task execution and improve program efficiency. Function as callback: Functions can be passed as parameters to other functions and be called when specific events or operations occur, providing a flexible callback mechanism.

PHP extensions can support object-oriented programming by designing custom functions to create objects, access properties, and call methods. First create a custom function to instantiate the object, and then define functions that get properties and call methods. In actual combat, we can customize the function to create a MyClass object, obtain its my_property attribute, and call its my_method method.

PHP's object-oriented programming paradigm provides advantages for project management and organization With the rapid development of the Internet, websites and applications of all sizes have sprung up. In order to meet the growing needs and improve development efficiency and maintainability, the use of object-oriented programming (Object-Oriented Programming, OOP for short) has become the mainstream of modern software development. In dynamic scripting languages like PHP, OOP brings many advantages to project management and organization. This article will introduce

What is object-oriented programming? Object-oriented programming (OOP) is a programming paradigm that abstracts real-world entities into classes and uses objects to represent these entities. Classes define the properties and behavior of objects, and objects instantiate classes. The main advantage of OOP is that it makes code easier to understand, maintain and reuse. Basic Concepts of OOP The main concepts of OOP include classes, objects, properties and methods. A class is the blueprint of an object, which defines its properties and behavior. An object is an instance of a class and has all the properties and behaviors of the class. Properties are characteristics of an object that can store data. Methods are functions of an object that can operate on the object's data. Advantages of OOP The main advantages of OOP include: Reusability: OOP can make the code more

1. Introduction to Python Python is a general-purpose programming language that is easy to learn and powerful. It was created by Guido van Rossum in 1991. Python's design philosophy emphasizes code readability and provides developers with rich libraries and tools to help them build various applications quickly and efficiently. 2. Python basic syntax The basic syntax of Python is similar to other programming languages, including variables, data types, operators, control flow statements, etc. Variables are used to store data. Data types define the data types that variables can store. Operators are used to perform various operations on data. Control flow statements are used to control the execution flow of the program. 3.Python data types in Python

Functional and Object-Oriented Programming (OOP) provide different programming mechanisms in C++: Function: independent block of code, focused on performing a specific task, containing no data. OOP: Based on objects, classes and inheritance, data and behavior are encapsulated in objects. In actual cases, the function method for calculating the area of a square is simple and direct, while the OOP method encapsulates data and behavior and is more suitable for managing object interaction. Choosing the appropriate approach depends on the scenario: functions are good for independent tasks, OOP is good for managing complex object interactions.
