Returning a value in constructor function of a class

后端 未结 8 553
情话喂你
情话喂你 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:40

    I'm really surprised that for 4 years none of the 22k viewers suggested creating private constructor and a method that attempts to create an object like this:

    class A {
        private function __construct () {
            echo "Created!\n";
        }
        public static function attemptToCreate ($should_it_succeed) {
            if ($should_it_succeed) {
                return new A();
            }
            return false;
        }
    }
    
    var_dump(A::attemptToCreate(0)); // bool(false)
    var_dump(A::attemptToCreate(1)); // object(A)#1 (0) {}
    //! new A(); - gives error
    

    This way you get either an object or false (you can also make it return null). Catching both situations is now very easy:

    $user = User::attemptToCreate('email@example.com');
    if(!$user) { // or if(is_null($user)) in case you return null instead of false
        echo "Not logged.";
    } else {
        echo $user->name; // e.g.
    }
    

    You can test it right here: http://ideone.com/TDqSyi

    I find my solution more convenient to use than throwing and catching exceptions.

    0 讨论(0)
  • 2020-11-27 17:45

    I wouldn't put too much in the construct. You should consider a static functin that create the User (factory) instead of putting everything in the constructor. Thus, you can still use your user object without having to call implicitly the load function. This will save you pain.

    public function __construct(){}
    
    public function setIdentifier($value){
        $this->identifier = $value;
    }
    
    public function load(){
        // whatever you need to load here
        //...
        throw new UserParameterNotSetException('identifier not set');
        // ...
        // if user cannot be loaded properly
        throw new UserNotFoundException('could not found user');
    }
    
    public static function loadUser($identifier){
        $user = new User();
        $user->setIdentifier($identifier);
        $user->load();
        return $user;
    }
    

    Sample usage:

    $user = new User(); 
    try{
        $user->setIdentifier('identifier');
        $user->load();
    }
    catch(UserParameterNotSetException $e){
        //...
    }
    catch(UserNotFoundException $e){
        // do whatever you need to do when user is not found
    }
    
    // With the factory static function:
    try{
        $user2 = User::loadUser('identifier');
    }
    catch(UserParameterNotSetException $e){
        //...
    }
    catch(UserNotFoundException $e){
        // do whatever you need to do when user is not found
    }
    
    0 讨论(0)
提交回复
热议问题