Returning a value in constructor function of a class

后端 未结 8 590
情话喂你
情话喂你 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.

提交回复
热议问题