Gowire
Gowire

Reputation: 1060

Can I return null instead of an object when a class fails to be initiated?

Is it possible to design a class constructor that destroys the object or sets it to null if it fails to initiate. For example in the code below - if a user isn't found in a database then it could be useful to set the object to Null (A)... or is it better to use a class member flag $found (B)?

<?php
class User {
    private $name = "";
    public  $found = true;

    function __construct($username) {
        if (!db_lookup_user($username)) {
            $this = null;           // A. This won't work - but can I return null instead of an object?
            $this->found = false;   // B. The alternative is to set a flag that indicates that the object is valid
        } else {
            $this->name = $username;
        }
    }
}

$myUser = new User("Donald Duck); 
if (is_null($myUser)) { echo "User doesn't exist"; }
   ... or ...
if ($myUser->found == false) { echo "User doesn't exist"; }

Upvotes: 1

Views: 486

Answers (2)

Edward Surov
Edward Surov

Reputation: 487

It's not possible to return null directly from within the __construct() method, but you can write a factory (or factory method) that returns null on failure, as Felippe showed above. But in general it's a dangerous pattern to return nullable values: in some moment you can just forget to check for null. You may like the null object pattern as an alternative.

Upvotes: 1

Felippe Duarte
Felippe Duarte

Reputation: 15131

You can use a Factory Pattern (https://en.wikipedia.org/wiki/Factory_method_pattern) (or something close to that)

<?php

class UserFactory {
    static function createUser($username) {
        if($username == 'something') {
            return new User();
        } else {
            return null;
        }
    }
}

class User {}

$user1 = UserFactory::createUser('something');
$user2 = UserFactory::createUser('somethingElse');
var_dump($user1,$user2);

output

object(User)#1 (0) {}
NULL

Upvotes: 2

Related Questions