w3resource

PHP class for rectangle: Area and perimeter calculation


1. Rectangle Class

Write a PHP class 'Rectangle' that has properties for length and width. Implement methods to calculate the rectangle's area and perimeter.

Sample Solution:

PHP Code :

<?php
class Rectangle {
    private $length;
    private $width;

    public function __construct($length, $width) {
        $this->length = $length;
        $this->width = $width;
    }

    public function getArea() {
        return $this->length * $this->width;
    }

    public function getPerimeter() {
        return 2 * ($this->length + $this->width);
    }
}

$rectangle = new Rectangle(12, 9);
echo "Area: " . $rectangle->getArea() . "</br>";
echo "Perimeter: " . $rectangle->getPerimeter() . "</br>";
?>

Sample Output:

Area: 108
Perimeter: 42

Explanation:

In the above exercise -

  • The "Rectangle" class has two private properties: $length and $width, which represent the rectangle's dimensions.
  • The constructor method __construct() initializes the rectangle's length and width.
  • The getArea() method calculates and returns the rectangle's area by multiplying its length and width.
  • The getPerimeter() method calculates and returns the rectangle perimeter using the formula: 2 * (length + width).

Flowchart:

Flowchart: Area and perimeter calculation.

For more Practice: Solve these Related Problems:

  • Write a PHP class that validates positive numeric values for length and width before calculating area and perimeter.
  • Write a PHP program that extends the Rectangle class to include a method for resizing the rectangle by a percentage.
  • Write a PHP class that overloads the __toString() magic method to display the rectangle's dimensions, area, and perimeter.
  • Write a PHP script to compare two Rectangle objects and determine which one has a larger area.

Go to:


PREV : PHP OOP Exercises Home.
NEXT : Circle Class.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.