Returning a value in constructor function of a class

后端 未结 8 589
情话喂你
情话喂你 2020-11-27 17:04

So far I have a PHP class with the constructor

public function __construct ($identifier = NULL)
{
 // Return me.
if ( $identifier != NULL )
{
           


        
8条回答
  •  余生分开走
    2020-11-27 17:39

    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
    }
    

提交回复
热议问题