PHP Multi-State Code instance _php instance

Source: Internet
Author: User

Polymorphic definition: Only one interface or base class is concerned, but not the specific class of an object. (same type, different result)

Here are two examples:

First, we found that the base class defines the criteria, and subclasses perform the implementation of the self rule. This is a requirement for polymorphism. At the same time, it is satisfying to rewrite; in fact, this is a different kind of performance; there is no strict satisfaction with an interface, or base class programming. Because you call the time is not Stu->showgrade () but their own methods;

Class stu{public

  function Showgrade () {
    echo ' base class ';  
  }

}


Class Xiaomin extends stu{public

  function Showgrade () {
    echo ' is ' son show ';  
  } 
}

Class Xiaoli extends stu{public

  function Showgrade () {
    echo ' is ' son show ';  
  }

function doit ($obj) {

  if (Get_class ($obj)!= "Stu") {
    $obj->showgrade ();
  }

}

Doit (new Xiaoli ());
Doit (new xiaomin ());

The second example: the Dovoice parameter stipulates the $obj as animal, the consciousness is to accept the implementation class object with the interface. The upward transition. This is consistent with the same type, different results, this is polymorphism;

Actually in Java it would be 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~~~<br>";
  }
}

Class Dog implements animal{public
  function voice () {
    echo "Wang ~~~<br>";
  }
}

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.