Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
96 views
in Technique[技术] by (71.8m points)

php - Returning a value in constructor function of a class

So far I have a PHP class with the constructor

public function __construct ($identifier = NULL)
{
 // Return me.
if ( $identifier != NULL )
{
  $this->emailAddress = $identifier;
  if ($this->loadUser() )
    return $this;      
  else
  {
// registered user requested , but not found ! 
return false;
  }
}

the functionality of loadUser is to look up the database for a particular email address. When i set the identifier to some email that i'm sure it's not in the database; the first IF is get passed, and goes to the first ELSE. here the constructor should return FALSE; but instead, it returns an object of the class with all NULL values !

how do i prevent this? thanks

EDIT:

thank you all for the answers. that was quite fast ! I see that the OOP way is to throw an Exception. So a throw one, my question changes that what should i do with the exception?? php.net's manual is pretty confusing !

    // Setup the user ( we assume he is a user first. referees, admins are   considered users too )
    try { $him = new user ($_emailAddress);
    } catch (Exception $e_u) { 
      // try the groups database
      try { $him = new group ($_emailAddress); 
      } catch (Exception $e_g) {
          // email address was not in any of them !!  
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Constructors don't get return values; they serve entirely to instantiate the class.

Without restructuring what you are already doing, you may consider using an exception here.

public function __construct ($identifier = NULL)
{
  $this->emailAddress = $identifier;
  $this->loadUser();
}

private function loadUser ()
{
    // try to load the user
    if (/* not able to load user */) {
        throw new Exception('Unable to load user using identifier: ' . $this->identifier);
    }
}

Now, you can create a new user in this fashion.

try {
    $user = new User('user@example.com');
} catch (Exception $e) {
    // unable to create the user using that id, handle the exception
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...