How can classes and functions be utilized to separate tasks in PHP scripts effectively?
Classes and functions can be utilized to separate tasks in PHP scripts effectively by encapsulating related functionality within classes and breaking down tasks into smaller, reusable functions. Classes allow for better organization of code by grouping related functions and variables together, while functions help break down complex tasks into smaller, more manageable parts. This approach promotes code reusability, maintainability, and readability.
// Example of utilizing classes and functions to separate tasks in PHP scripts
class Calculator {
public function add($num1, $num2) {
return $num1 + $num2;
}
public function subtract($num1, $num2) {
return $num1 - $num2;
}
}
$calculator = new Calculator();
$result1 = $calculator->add(5, 3);
$result2 = $calculator->subtract(10, 2);
echo "Result of addition: " . $result1 . "<br>";
echo "Result of subtraction: " . $result2;