Menu
Coddy logo textTech

Recap - Shape Calculator

Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 32 of 91.

challenge icon

Challenge

Easy

Let's build a shape calculator that demonstrates the power of interfaces for creating flexible, extensible code. You'll create an interface that defines a contract for calculating areas, then implement it in different shape classes.

You'll organize your code across four files:

  • Calculable.php — Define a Calculable interface with a single method signature: calculateArea(). This contract ensures any calculable shape can compute its area.
  • Rectangle.php — Create a Rectangle class that implements Calculable. Include the interface file. The class should have private $width and $height properties, set through the constructor. Implement calculateArea() to return the area (width multiplied by height).
  • Circle.php — Create a Circle class that also implements Calculable. Include the interface file. The class should have a private $radius property, set through the constructor. Implement calculateArea() to return the area using the formula pi() * radius * radius.
  • main.php — Include both shape files. Create a function called displayArea that accepts a Calculable parameter and a shape name (string). The function should print: "[name] area: [area]" where the area is rounded to 2 decimal places using number_format().

You'll receive four inputs: rectangle width, rectangle height, circle radius, and a shape name for the circle. Create a Rectangle with the width and height (convert to floats), and a Circle with the radius (convert to float). Call displayArea() twice — first with the rectangle using "Rectangle" as the name, then with the circle using the provided shape name. Print each result on its own line.

The displayArea() function works with any shape that implements Calculable — it doesn't need to know whether it's calculating the area of a rectangle, circle, or any future shape you might add. That's the beauty of programming to an interface!

Try it yourself

<?php
// Include the shape files
require_once 'Rectangle.php';
require_once 'Circle.php';

// TODO: Create a function called displayArea
// It should accept a Calculable parameter and a shape name (string)
// Print: "[name] area: [area]" where area is rounded to 2 decimal places using number_format()

// Read inputs
$width = floatval(trim(fgets(STDIN)));
$height = floatval(trim(fgets(STDIN)));
$radius = floatval(trim(fgets(STDIN)));
$circleName = trim(fgets(STDIN));

// TODO: Create a Rectangle with the width and height

// TODO: Create a Circle with the radius

// TODO: Call displayArea() with the rectangle using "Rectangle" as the name

// TODO: Call displayArea() with the circle using the provided shape name
?>

All lessons in Object Oriented Programming