Home >Backend Development >PHP Tutorial >A case of implementing object-oriented polymorphism method in PHP

A case of implementing object-oriented polymorphism method in PHP

黄舟
黄舟Original
2017-09-28 09:02:511375browse

This article mainly introduces the method of realizing object-oriented polymorphism in PHP. It briefly explains the principle of object-oriented polymorphism and gives relevant operating techniques for realizing polymorphism in PHP based on specific examples. Friends in need can refer to it. Next

The examples in this article describe the object-oriented polymorphic implementation method of PHP. Share it with everyone for your reference, the details are as follows:

Polymorphism: The parent class reference points to the subclass object (in object-oriented, different calls can be made based on the context of using the class (using different input classes) Class methods) to redefine or change the properties and behavior of the class); the interface reference points to the class object that implements the interface.

Object-oriented: Form data (properties), methods of operating data, and logic into a class, abstract the class to form an object, and use the class through the object;


<?php
class work{
  function polymorphic($obj){
    //检查是否引用类型(obj是否继承animal类)
    if($obj instanceof animal){
      $obj -> fun();
    }
    else{
      echo "no function";
    }
  }
  //如果需要指定类 (指定cat类,包含cat子类)
  function bose(cat $obj){
    $obj->fun();
  }
}
//抽象类
 abstract class animal{
  abstract function fun();
}
//cat猫类
class cat extends animal{
  function fun(){
    echo "cat say miaomiao...";
  }
}
//dog狗类
class dog extends animal{
  function fun(){
    echo "dog say wangwang...";
  }
}
class mouse extends cat{
}
//先new一个work类
$new_work = new work();
//然后通过new_work对象 调用 polymorphic 方法,传入不同的类实现 父类引用指向子类对象;接口引用指向实现接口的类对象(多态)。
$new_work->polymorphic(new cat());
echo &#39;<br/>&#39;;
$new_work->polymorphic(new dog());
echo &#39;<br/>&#39;;
//指定类方式仿java
$new_work->bose(new cat());
echo &#39;<br/>&#39;;
//如果传输其他类,或者未继承cat类则会报错
//$new_work->bose(new dog());
echo &#39;<br />&#39;;
//这也不会报错
$new_work->bose(new mouse());

Running results:


cat say miaomiao...
dog say wangwang...
cat say miaomiao...

cat say miaomiao...

The above is the detailed content of A case of implementing object-oriented polymorphism method 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