PHP multi-state code instance _ php instance

Source: Internet
Author: User
This article mainly introduces PHP multi-state code instances. This article uses two code instances to demonstrate the polymorphism in PHP. For more information, see the following multi-state definition: Only one interface or a base class is concerned, does not care about the specific class of an object. (Same type, different results)

Here are two examples:

First, we found that the base class defines standards and sub-classes implement self-rules. This is a requirement for polymorphism. At the same time, this satisfies rewriting; in fact, this is different performance of different classes; it does not strictly satisfy an interface, or it is a base class programming. This is because the method you call is not stu-> showGrade () but your own method;

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());

Example 2: The dovoice parameter specifies that $ obj is an animal, and consciousness means that the implementation class object is accepted by the interface. Is transformed upwards. This is consistent with the same type and different results. This is polymorphism;

In Java, it will be like animal a = new dog (); Because PHP is a type language. There is no object transformation mechanism.

interface animal{  public function voice();}class cat implements animal{  public function voice(){    echo "miao~~~
"; }}class dog implements animal{ public function voice(){ echo "wang ~~~
"; }}function dovoice(animal $obj){ $obj->voice();}dovoice(new dog());dovoice(new cat());

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.