I have a User class that will throw an exception if the userid provided in the parameter does not correspond with a user.
I've written a helper function that will return true or false depending on whether a userid belongs to a user or not, but was wondering if my use of a try {} catch {} to do so is correct:
private function userExists($userid)
{
$user_does_not_exist = false;
try
{
$user = new User($userid);
}
catch (Exception $e)
{
$user_does_not_exist = true;
}
return $user_does_not_exist;
}
Any and all critique is greatly appreciated.
1 Answer 1
I would suggest working the other way around. Expect that a user does not exist and only return true if a user is found.
private function UserExists($userId)
{
$userExists = false;
try
{
$user = new User($userId);
if($user !== null)
$userExists = true;
}
catch (Exception $e)
{
//handle exception
}
return $userExists;
}
You can drive this further and ease things by not using a variable to return, like this:
private function UserExists($userId)
{
try
{
return new User($userId) !== null;
}
catch (Exception $e)
{
return false;
}
}