How can functions and classes be organized and managed in PHP to improve code reusability and maintainability?
To improve code reusability and maintainability in PHP, functions and classes can be organized and managed by following principles such as separation of concerns, single responsibility, and DRY (Don't Repeat Yourself). By breaking down code into smaller, modular functions and classes, it becomes easier to reuse them in different parts of the application and maintain them over time.
// Example of organizing functions and classes in PHP for improved reusability and maintainability
// Define a function for a specific task
function calculateSum($a, $b) {
return $a + $b;
}
// Define a class with related methods
class User {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function greet() {
return "Hello, " . $this->name;
}
}
// Example usage of the function and class
$sum = calculateSum(5, 3);
echo $sum; // Output: 8
$user = new User("John");
echo $user->greet(); // Output: Hello, John