php object-oriented - polymorphism
First explain polymorphism: PHP object-oriented polymorphism refers to defining the methods implemented by subclasses through an abstract class or interface, and then passing in the instantiation of each previously defined subclass in a function or class method. The object name is used to implement different execution logic for different objects by calling the same method in the new class (due to different parameters). (My own understanding, unofficial).
Here is an example:
//Define parent class interface
interface Person{
function getName();
function getAge();
}
//First subclass
class Phper implements Person{
public function getName()
{
echo 'this is php'getName';
}
public function getAge()
{
echo 'this is php'getAge';
}
}
//Second subclass
class Javaer implements Person{
public function getName()
{
echo 'this is jave'getName';
}
public function getAge()
{
echo 'this is java'getAge';
}
}
//A brand new class
class my{
function isMy($obj)//The parameter here is an object name
{
$obj->getName();
echo "
";
$obj->getAge();
}
}
//Instantiate the previous classes respectively
$php = new Phper;
$java = new Javaer;
$my = new My;
$my->isMy($java);//Execute different business logic by passing in the names of different objects
?>
If you want to ask me what is the use of this thing, then I can only say that it may be helpful in standardizing and understanding the code. I don’t know about other things, because I don’t have any in the actual work process. I have encountered scenarios where polymorphism is used.
I hope bloggers who have new insights or better cases can give explanations or links in the comments.
http://www.bkjia.com/PHPjc/1071708.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1071708.htmlTechArticlephp object-oriented - polymorphism First explain polymorphism: php object-oriented polymorphism refers to the use of an abstraction The class or interface defines the methods implemented by the subclass, and then in a function or class...
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