In PHP, what are some best practices for setting values, such as email recipients, within a class using functions?

When setting values within a class using functions in PHP, it is a best practice to use setter methods to encapsulate the logic for setting the values. This helps maintain the integrity of the class by controlling access to its properties and allows for validation or manipulation of the values before they are set. By using setter methods, you can also easily update the implementation of how values are set without affecting other parts of the code that interact with the class.

class EmailSender {
    private $recipient;

    public function setRecipient($email) {
        // Add validation logic here if needed
        $this->recipient = $email;
    }

    public function sendEmail($message) {
        // Send email to $this->recipient
    }
}

$emailSender = new EmailSender();
$emailSender->setRecipient('recipient@example.com');
$emailSender->sendEmail('Hello there!');