Area and Perimeter of Rectangle using a Class
Calculating the area and perimeter of a rectangle is by defining a class to represent a rectangle and including separate methods for calculating the area and perimeter, namely calculateArea and calculatePerimeter .
Example: Illustration of calculating the area and perimeter of a rectangle in PHP using classes.
PHP
<?php class Rectangle { public $length ; public $width ; public function __construct( $length , $width ) { $this ->length = $length ; $this ->width = $width ; } // To calculate the area public function calculateArea() { return $this ->length * $this ->width; } // To calculate the area public function calculatePerimeter() { return 2 * ( $this ->length + $this ->width); } } // Driver code $rectangle = new Rectangle(10, 5); $area = $rectangle ->calculateArea(); $perimeter = $rectangle ->calculatePerimeter(); echo "Area of the rectangle: $area\n" ; echo "Perimeter of the rectangle: $perimeter" ; ?> |
Output
Area of the rectangle: 50 Perimeter of the rectangle: 30
Time Complexity: O(1)
Auxiliary Space: O(1)
PHP Program to Find Area and Perimeter of Rectangle
Calculating the area and perimeter of a rectangle is a fundamental geometric operation. The area of a rectangle is given by the formula Area = length * width
, and the perimeter is given by Perimeter = 2 * (length + width)
. In this article, we will explore how to calculate the area and perimeter of a rectangle in PHP using different approaches.
Table of Content
- Area and Perimeter of Rectangle using Functions
- Area and Perimeter of Rectangle using a Class
Contact Us