Home >Backend Development >PHP Tutorial >Polymorphism in PHP

Polymorphism in PHP

墨辰丷
墨辰丷Original
2018-06-09 11:57:046299browse

This article mainly introduces polymorphism in PHP. Interested friends can refer to it. I hope it will be helpful to everyone.

Polymorphic definition: only care about an interface or base class, not the specific class of an object. (Same type, different results)

Here are two examples:

First, we found that the base class defines the standard and the subclass implements its own rules. This is a requirement of polymorphism. At the same time, this is to satisfy rewriting; in fact, it is a different performance of different classes; it does not strictly satisfy an interface or base class programming. Because when you call it is not stu->showGrade() but each of its own methods;


class stu{

  public function showGrade(){
    echo "base class";  
  }

}


class xiaomin extends stu{

  public function showGrade(){
    echo "is son show 80";  
  } 
}

class xiaoli extends stu{

  public function showGrade(){
    echo "is son show 60";  
  } 
}

function doit($obj){

  if(get_class($obj) != "stu"){
    $obj->showGrade();
  }

}

doit(new xiaoli());
doit(new xiaomin());


Second example: The dovoice parameter stipulates that $obj is animal, which means that the implementation class object is accepted through the interface. An upward transformation. This is consistent with the same type but different results. This is polymorphism;

In fact, in Java, it will be animal a = new dog(); like this; because PHP is a typed language. There is no object conversion mechanism.


interface animal{
  public function voice();
}

class cat implements animal{
  public function voice(){
    echo "miao~~~<br>";
  }
}

class dog implements animal{
  public function voice(){
    echo "wang ~~~<br>";
  }
}

function dovoice(animal $obj){
  $obj->voice();
}


dovoice(new dog());
dovoice(new cat());

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

php Unordered Tree Implementation Skills

php Unordered Tree Implementation skills

php operates image size modification, watermarking, generating verification code, output and saving

##

The above is the detailed content of Polymorphism in PHP. For more information, please follow other related articles on the PHP Chinese website!

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