Home Backend Development PHP Tutorial Two implementations of polymorphism in PHP, overloading and overriding

Two implementations of polymorphism in PHP, overloading and overriding

Jun 05, 2018 pm 04:15 PM
php object-oriented

This article mainly introduces the two implementations of polymorphism in PHP, overloading and overwriting. Interested friends can refer to it. I hope it will be helpful to everyone. 2

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 these functions with the same name can be distinguished by the number or parameter types of the function, so that there is no confusion in the call. That is, when called, although the method names are the same, the corresponding functions can be automatically called according to different parameters.

1

2

3

4

5

6

7

8

9

10

11

class A{

  public function test(){

    echo "test1";

  }

  public function test($a){

    echo "test2";

  }

}

$a=new A();

$a->test();

$a->test($a);

Copy after login

If php directly supports method overloading. Then after the above example is executed, different values ​​will be returned if parameters are passed and if parameters are not 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.

1

public function test($a){

Copy after login

So php does not directly support overloading. 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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

public function __call($method,$p)

{

  if($method=="display"){

    if(is_object($p[0])){

      $this->displayObject($p[0]);

    }else if(is_array($p[0])){

      $this->displayArray($p[0]);

    }else{

      $this->displayScalar($p[0]);

    }

  }

}

//下面是对上面定义的调用

$ov=new overload;

$ov->display(array(1,2,3));

$ov->display('cat');

Copy after login

When defining the 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; If other content is passed, 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 (override)

The so-called override 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.

There are the following requirements:

#1. When a parent class and a subclass have a method, and the parameters and names are exactly the same, then Subclass methods override parent class methods.

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 and names are required to be the same. 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:

1

2

3

4

5

6

7

8

9

10

11

12

class people{

  protected function sing(){

    echo "人唱歌";

  }

}

class woman extends people{

  public function sing(){

    echo "女人唱歌";

  }

}

$woman1=new woman();

$woman1->sing();

Copy after login

This is normal and can 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.

第三点,是要求参数和名字一样,具体就是要求参数的个数与父类相同,而并不是参数名称一致。即传递的参数名字可以为任意,只要保证传递的个数相同即可。

以上内容简单介绍了PHP语言中多态的两个实现。

PS:重写、覆盖、重载、多态几个概念的区别分析

override->重写(=覆盖)、overload->重载、polymorphism -> 多态

override是重写(覆盖)了一个方法,以实现不同的功能。一般是用于子类在继承父类时,重写(重新实现)父类中的方法。
重写(覆盖)的规则:

1、重写方法的参数列表必须完全与被重写的方法的相同,否则不能称其为重写而是重载.
2、重写方法的访问修饰符一定要大于被重写方法的访问修饰符(public>protected>default>private)。
3、重写的方法的返回值必须和被重写的方法的返回一致;
4、重写的方法所抛出的异常必须和被重写方法的所抛出的异常一致,或者是其子类;
5、被重写的方法不能为private,否则在其子类中只是新定义了一个方法,并没有对其进行重写。
6、静态方法不能被重写为非静态的方法(会编译出错)。

overload是重载,一般是用于在一个类内实现若干重载的方法,这些方法的名称相同而参数形式不同。

重载的规则:

1、在使用重载时只能通过相同的方法名、不同的参数形式实现。不同的参数类型可以是不同的参数类型,不同的参数个数,不同的参数顺序(参数类型必须不一样);
2、不能通过访问权限、返回类型、抛出的异常进行重载;
3、方法的异常类型和数目不会对重载造成影响;

多态的概念比较复杂,有多种意义的多态,一个有趣但不严谨的说法是:继承是子类使用父类的方法,而多态则是父类使用子类的方法。

一般,我们使用多态是为了避免在父类里大量重载引起代码臃肿且难于维护。

举个例子:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

public class Shape

{

  public static void main(String[] args){

   Triangle tri = new Triangle();

   System.out.println("Triangle is a type of shape? " + tri.isShape());// 继承

   Shape shape = new Triangle();

   System.out.println("My shape has " + shape.getSides() + " sides."); // 多态

   Rectangle Rec = new Rectangle();

   Shape shape2 = Rec;

   System.out.println("My shape has " + shape2.getSides(Rec) + " sides."); //重载

  }

  public boolean isShape(){

   return true;

  }

  public int getSides(){

   return 0 ;

  }

  public int getSides(Triangle tri){ //重载

   return 3 ;

  }

  public int getSides(Rectangle rec){ //重载

  return 4 ;

  }

}

class Triangle extends Shape

{

  public int getSides() { //重写,实现多态

   return 3;

  }

}

class Rectangle extends Shape

{

  public int getSides(int i) { //重载

  return i;

  }

}

Copy after login

总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。

相关推荐:

PHP实现导出带样式的Excel实例分享

php解决和避免form表单重复提交的方法

PHP简单字符串过滤方法实例分享

The above is the detailed content of Two implementations of polymorphism in PHP, overloading and overriding. 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

Video Face Swap

Video Face Swap

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

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)

An in-depth explanation of PHP's object-oriented encapsulation An in-depth explanation of PHP's object-oriented encapsulation Aug 11, 2023 am 11:00 AM

In-depth interpretation of PHP object-oriented encapsulation Encapsulation is one of the three major characteristics of object-oriented programming. It refers to encapsulating data and operations on data in a class, hiding specific implementation details from external programs, and providing external interfaces. In PHP, the concept of encapsulation is implemented by using access modifiers (public, protected, private) to control the accessibility of properties and methods. First, let’s take a look at the role of access modifiers: public (public): Public properties and methods can

How to implement object version control and management through PHP object-oriented simple factory pattern How to implement object version control and management through PHP object-oriented simple factory pattern Sep 06, 2023 pm 02:39 PM

How to implement object version control and management through the PHP object-oriented simple factory model. When developing large and complex PHP projects, version control and management are very important. Through appropriate design patterns, we can better manage and control the creation and use of objects, thereby improving the maintainability and scalability of the code. This article will introduce how to use the PHP object-oriented simple factory pattern to implement object version control and management. The simple factory pattern is a design pattern for creating classes that instantiates specified objects through a factory class

How to achieve seamless switching and replacement of objects through PHP object-oriented simple factory pattern How to achieve seamless switching and replacement of objects through PHP object-oriented simple factory pattern Sep 06, 2023 am 08:01 AM

How to achieve seamless switching and replacement of objects through PHP's object-oriented simple factory pattern Introduction: In PHP development, object-oriented programming (Object-oriented Programming, referred to as OOP) is a very common programming paradigm. The object-oriented design pattern can further improve the maintainability and scalability of the code. This article will focus on the simple factory pattern in PHP to achieve seamless switching and replacement of objects. What is the simple factory pattern? Simple factory pattern (Simple

How to create flexible object instances using PHP object-oriented simple factory pattern How to create flexible object instances using PHP object-oriented simple factory pattern Sep 06, 2023 pm 02:12 PM

How to create flexible object instances using the PHP object-oriented simple factory pattern. The simple factory pattern is a common design pattern that creates object instances without exposing object creation logic. This mode can improve the flexibility and maintainability of the code, and is especially suitable for scenarios where different objects need to be dynamically created based on input conditions. In PHP, we can use the characteristics of object-oriented programming to implement the simple factory pattern. Let's look at an example below. Suppose we need to create a graphing calculator that can

How to master object-oriented programming skills in PHP development How to master object-oriented programming skills in PHP development Jun 25, 2023 am 08:05 AM

With the development of the Internet, PHP has gradually become one of the most popular programming languages ​​​​in web development. However, with the rapid development of PHP, object-oriented programming has become one of the necessary skills in PHP development. In this article, we will discuss how to master object-oriented programming skills in PHP development. Understanding the Concepts of Object-Oriented Programming Object-oriented programming is a programming paradigm that organizes code and data through the use of objects (classes, properties, and methods). In object-oriented programming, code is organized into reusable modules, thereby improving the program's

Understand the object-oriented inheritance mechanism of PHP Understand the object-oriented inheritance mechanism of PHP Aug 10, 2023 am 10:40 AM

Understanding the Object-Oriented Inheritance Mechanism of PHP Inheritance is an important concept in object-oriented programming, which allows the creation of new classes that include the features and functionality of the old classes. In PHP, inheritance can be achieved through the keyword extends. Through inheritance, subclasses can inherit the properties and methods of the parent class, and can add new properties and methods, or override inherited methods. Let us understand the object-oriented inheritance mechanism of PHP through an example. classAnimal{public$name

How PHP implements object-oriented programming and improves code readability and maintainability How PHP implements object-oriented programming and improves code readability and maintainability Jun 27, 2023 pm 12:28 PM

With the continuous development of Internet technology, PHP has become one of our common website development languages, and PHP object-oriented programming has also become a knowledge point that must be learned. Object-oriented programming (OOP) is a programming paradigm whose core concept is to combine data and behavior into an object to improve code reusability, readability, and maintainability. This article will explore how to use PHP to implement object-oriented programming and improve the readability and maintainability of your code. Basic Concepts of Object-Oriented Programming In object-oriented programming, each object has a set of properties.

Detailed explanation of common problems in PHP object-oriented programming Detailed explanation of common problems in PHP object-oriented programming Jun 09, 2023 am 09:27 AM

PHP language has become a very popular web development language because it is easy to learn and use. Object-oriented programming is one of the most important programming paradigms in the PHP language. However, object-oriented programming is not something that is easy to master, so some common problems often arise. In this article, we will provide a detailed analysis of common problems with object-oriented programming in PHP. Question 1: How to create an object? In PHP, you can use the new keyword to create an object. For example: classMyClass{/

See all articles