Get Website Learn Coding Tech Story

PHP Programming Examples

<?php
	/* Parent class */
	class animal {
		
		/* Protected variables */
		protected $name;
		protected $blood;
		
		/* Constructor of the class */
		function __construct($nm, $bld) {
			$this->name = $nm;
			$this->blood= $bld;
		}
	}
	
	/* Child class */
	class mammals extends animal {
		protected $legs;
		
		function __construct($nm, $bld, $lgs) {
			
			/* Call constructor of the parent class */
			parent::__construct($nm, $bld);
			$this->legs = $lgs;
		}
		
		function display() {
			echo "<br />Name of the Animal: ".$this->name;
			echo "<br />Blood: ".$this->blood;
			echo "<br />No of Legs: ".$this->legs;
		}
	}
	
	/* Child class */
	class reptiles extends animal {
		protected $venom;
		
		function __construct($nm, $bld, $ven) {
			
			/* Call constructor of the parent class */
			parent::__construct($nm, $bld);
			$this->venom = $ven;
		}
		
		function display() {
			echo "<br />Name of the Animal: ".$this->name;
			echo "<br />Blood: ".$this->blood;
			echo "<br />Venom: ".$this->venom;
		}
	}
	
	/* Object of the child class */
	$elephant = new mammals("Elephant", "Worm", "4");
	$elephant->display();

	echo "<br />";
	
	/* Object of the child class */
	$snake = new mammals("King Cobra", "Cold", "Neurotoxin");
	$snake->display();
?>


          /****** Output ******/
          

Name of the Animal: Elephant


Blood: Worm


No of Legs: 4




Name of the Animal: King Cobra


Blood: Cold


No of Legs: Neurotoxin

Learn more about inheritance