Recap - Shape Calculator
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 32 of 91.
Challenge
EasyLet'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 aCalculableinterface with a single method signature:calculateArea(). This contract ensures any calculable shape can compute its area.Rectangle.php— Create aRectangleclass that implementsCalculable. Include the interface file. The class should have private$widthand$heightproperties, set through the constructor. ImplementcalculateArea()to return the area (width multiplied by height).Circle.php— Create aCircleclass that also implementsCalculable. Include the interface file. The class should have a private$radiusproperty, set through the constructor. ImplementcalculateArea()to return the area using the formulapi() * radius * radius.main.php— Include both shape files. Create a function calleddisplayAreathat accepts aCalculableparameter and a shape name (string). The function should print:"[name] area: [area]"where the area is rounded to 2 decimal places usingnumber_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
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern