Thu May 21 2020

Method Overriding

PHP Scripting1188 views

File Name: method-overriding.php

<?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

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.