php: Examples of object inheritance and polymorphism

黄舟
Release: 2023-03-12 11:20:02
Original
1128 people have browsed it

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 &#39;这句话不会显示。&#39;;
		}
		
	}
	/*  子类Book  */
	class Book extends MyObject{
		
		public $book_type;									//类别
		
		function construct($type,$num){
			
			$this -> book_type = $type;
			$this -> object_num = $num;
		}
		
		function showMe(){
			
			return &#39;本次新进&#39;.$this -> book_type.&#39;图书&#39;.$this -> object_num.&#39;<br>&#39;;
		}
	}
	/*  子类Elec  */
	class Elec extends MyObject{
	
		function showMe(){
			
			return &#39;热卖商品&#39;.$this -> object_name.&#39;<br>原价:&#39;.$this -> object_price.&#39;<br>特价:&#39;.$this -> object_agio * $this -> object_price;
		}
	}
	/*	实例化对象	*/
	$c_book = new Book(&#39;计算机类&#39;,1000);
	$h_elec = new Elec(&#39;待机王XX手机&#39;,1200,3,0.8);
	echo $c_book->showMe()."<br>";
	echo $h_elec->showMe();
	
	
?>
Copy after login

(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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!