Skip to content
PHP Logo

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.

php
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
    }
}