How can returning true/false in methods improve object-oriented programming practices in PHP?
Returning true/false in methods can improve object-oriented programming practices in PHP by providing a clear indication of whether a method was successful or not. This helps in making the code more readable and maintainable. It also allows for better error handling and decision-making within the program.
class User {
private $loggedIn = false;
public function login($username, $password) {
// Perform login logic
if ($loginSuccessful) {
$this->loggedIn = true;
return true;
} else {
return false;
}
}
public function isLoggedIn() {
return $this->loggedIn;
}
}
$user = new User();
if ($user->login('username', 'password')) {
echo 'Login successful!';
} else {
echo 'Login failed.';
}