How can object-oriented programming principles be applied to enhance the functionality and efficiency of the provided PHP code?
Issue: The provided PHP code lacks proper organization and structure, making it difficult to maintain and extend. By applying object-oriented programming principles such as encapsulation, inheritance, and polymorphism, we can enhance the functionality and efficiency of the code.
<?php
// Define a class for better organization and encapsulation
class Calculator {
// Add methods to perform calculations
public function add($num1, $num2) {
return $num1 + $num2;
}
public function subtract($num1, $num2) {
return $num1 - $num2;
}
public function multiply($num1, $num2) {
return $num1 * $num2;
}
public function divide($num1, $num2) {
if ($num2 == 0) {
return "Cannot divide by zero";
}
return $num1 / $num2;
}
}
// Create an instance of the Calculator class
$calculator = new Calculator();
// Use the methods of the Calculator class to perform calculations
echo $calculator->add(5, 3); // Output: 8
echo $calculator->subtract(5, 3); // Output: 2
echo $calculator->multiply(5, 3); // Output: 15
echo $calculator->divide(6, 3); // Output: 2
?>