PHP Scripting

Method Overriding

Method overriding example for area calculation in php

5/21/2020
0 views
method-overriding.phpPHP
<?php
	/* Parent class */
	class square{
		public $height = 0;
		function __construct($h) {
			$this->height = $h;
		}
		
		function area() {
			return ($this->height * $this->height);
		}
	}
	
	/* Child class */
	class rectangle extends square {
		public $width = 0;
		function __construct($h, $w) {
			$this->height = $h;
			$this->width = $w;
		}
		
		/* Declare method with same name in child class */
		function area() {
			return ($this->height * $this->width);
		}
	}
	
	$sq = new square(6);
	echo "Area of a Square: ".$sq->area();
	
	$rec = new rectangle(8,4);
	echo "<br />Area of a Rectangle: ".$rec->area();
?>



/* Output */
Area of a Square: 36
Area of a Rectangle: 32
phpmethod overridingoop

Related Examples