How should classes in PHP be structured to adhere to the principle of single responsibility?
Classes in PHP should be structured so that each class has a single responsibility, meaning it should only have one reason to change. This can be achieved by breaking down the functionality into smaller, cohesive classes that handle specific tasks. By following this principle, classes become more maintainable, reusable, and easier to understand.
class User {
private $name;
private $email;
public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
}
public function getName() {
return $this->name;
}
public function getEmail() {
return $this->email;
}
}
class EmailSender {
public function sendEmail($user, $message) {
// Code to send email
}
}
Related questions
-
PHP data retrieval linking tables
-
PHP SQL queries variables
-
What are the advantages of using PHP functions like strip_tags() for sanitizing user input in forms?PHP functions strip_tags()