Recap - Simple Calculator
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 9 of 91.
Challenge
MediumBuild a complete Calculator class in calculator.php that demonstrates all OOP concepts you've learned. The driver.php file will import and test your class.
Your Calculator class should include:
- Property: A
public $resultproperty to store the running total - Constructor (
__construct): Initialize$resultto0and print"Calculator ready" - Destructor (
__destruct): Print"Calculator shutting down" - Methods that each use
$thisto update and return the result:add($number)— adds the number to resultsubtract($number)— subtracts the number from resultmultiply($number)— multiplies result by the numberdivide($number)— divides result by the number using integer division (intdiv). If the number is0, print"Error: Division by zero"and return the unchanged resultclear()— resets result to0getResult()— returns the current result
All arithmetic methods must return the new result after the operation.
Example usage:
require_once 'calculator.php';
$calc = new Calculator(); // prints: Calculator ready
$calc->add(5); // result becomes 5
$calc->multiply(3); // result becomes 15
$calc->subtract(2); // result becomes 13
$calc->divide(0); // prints: Error: Division by zero (result stays 13)
$calc->divide(2); // result becomes 6 (integer division)
$calc->clear(); // result becomes 0
// When script ends: prints Calculator shutting downTry it yourself
<?php
require_once 'calculator.php';
$testCase = trim(fgets(STDIN));
if ($testCase == "constructor_test") {
$calc = new Calculator();
echo "Initial result: " . $calc->getResult() . "\n";
echo "Calculator created successfully\n";
} elseif ($testCase == "addition_test") {
$calc = new Calculator();
$result1 = $calc->add(10);
echo "After adding 10: " . $result1 . "\n";
$result2 = $calc->add(5);
echo "After adding 5: " . $result2 . "\n";
echo "Final result: " . $calc->getResult() . "\n";
} elseif ($testCase == "subtraction_test") {
$calc = new Calculator();
$calc->add(20);
$result1 = $calc->subtract(8);
echo "After subtracting 8 from 20: " . $result1 . "\n";
$result2 = $calc->subtract(2);
echo "After subtracting 2: " . $result2 . "\n";
echo "Final result: " . $calc->getResult() . "\n";
} elseif ($testCase == "multiplication_test") {
$calc = new Calculator();
$calc->add(5);
$result1 = $calc->multiply(4);
echo "After multiplying by 4: " . $result1 . "\n";
$result2 = $calc->multiply(2);
echo "After multiplying by 2: " . $result2 . "\n";
echo "Final result: " . $calc->getResult() . "\n";
} elseif ($testCase == "division_test") {
$calc = new Calculator();
$calc->add(100);
$result1 = $calc->divide(4);
echo "After dividing by 4: " . $result1 . "\n";
$result2 = $calc->divide(5);
echo "After dividing by 5: " . $result2 . "\n";
echo "Final result: " . $calc->getResult() . "\n";
} elseif ($testCase == "division_by_zero_test") {
$calc = new Calculator();
$calc->add(50);
echo "Initial value: " . $calc->getResult() . "\n";
$result = $calc->divide(0);
echo "Result after division by zero: " . $result . "\n";
echo "Value unchanged: " . $calc->getResult() . "\n";
} elseif ($testCase == "clear_test") {
$calc = new Calculator();
$calc->add(25);
$calc->multiply(3);
echo "Before clear: " . $calc->getResult() . "\n";
$result = $calc->clear();
echo "After clear: " . $result . "\n";
echo "Current result: " . $calc->getResult() . "\n";
} elseif ($testCase == "comprehensive_test") {
$calc = new Calculator();
$calc->add(10);
$calc->multiply(3);
$calc->subtract(5);
$calc->divide(5);
echo "After sequence of operations: " . $calc->getResult() . "\n";
$calc->divide(0);
echo "After division by zero attempt: " . $calc->getResult() . "\n";
$calc->clear();
$calc->add(100);
echo "After clear and add 100: " . $calc->getResult() . "\n";
} else {
echo "Unknown test case\n";
}
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