Home > Article > Backend Development > php: Examples of object inheritance and polymorphism
This example uses the MyObject class to generate two subclasses: Book and Elec. The two subclasses use different construction methods to instantiate two objects c_book and h_elec, and Output information
<?php /*父类*/ class MyObject{ public $object_name; //名称 public $object_price; //价格 public $object_num; //数量 public $object_agio; //折扣 function construct($name,$price,$num,$agio){ $this -> object_name = $name; $this -> object_price = $price; $this -> object_num = $num; $this -> object_agio = $agio; } function showMe(){ echo '这句话不会显示。'; } } /* 子类Book */ class Book extends MyObject{ public $book_type; //类别 function construct($type,$num){ $this -> book_type = $type; $this -> object_num = $num; } function showMe(){ return '本次新进'.$this -> book_type.'图书'.$this -> object_num.'<br>'; } } /* 子类Elec */ class Elec extends MyObject{ function showMe(){ return '热卖商品'.$this -> object_name.'<br>原价:'.$this -> object_price.'<br>特价:'.$this -> object_agio * $this -> object_price; } } /* 实例化对象 */ $c_book = new Book('计算机类',1000); $h_elec = new Elec('待机王XX手机',1200,3,0.8); echo $c_book->showMe()."<br>"; echo $h_elec->showMe(); ?>
(1) The subclass inherits all member variables and methods of the parent class, including constructor. This is the implementation of inheritance
(2) When a subclass is created, PHP will first search for the constructor method in the subclass. If the subclass has its own constructor, PHP will give priority to calling the constructor of the subclass; when the subclass does not have one, PHP will call the constructor of the parent class
(3) The subclass overrides the parent class method showMe(), so although both objects call the showMe() method, the results returned are two different information. This is the embodiment of polymorphism
The above is the detailed content of php: Examples of object inheritance and polymorphism. For more information, please follow other related articles on the PHP Chinese website!