Consider the following, simple class constructor. (note that I am obviously not including all methods that are referenced.
// Initialize User class.
public function __construct($user_id = NULL)
{
// If user is loaded (and a user ID is provided)
if ($user_id)
{
// If user is authorized.
if ($this->authorized($user_id))
{
// Load user information.
$this->info = $this->load($user_id);
}
else
{
// Return an empty (nonexistent) user.
return NULL;
}
}
// If user is loaded (and no user ID is provided)
else
{
// Create a new user.
$new_user = create_user();
// Return the new user's ID.
return $new_user;
}
}
My question is this: is my method of returning values here wrong? My friend insists that a constructor should ALWAYS return an object NO MATTER WHAT. However, the way I have it laid out here seems much simpler, and is much easier to work with. (If I am making a new user, then I get his ID right off the bat. If I am loading an existing user, I immediately have access to her/his information)
If it IS wrong, why? Why is this bad?
What you’re trying to do simply doesn’t work, the constructor will return the new instance of
Useranyway, even when you try to returnnull.For example, this:
will print:
http://codepad.org/0IdJydkY