首页 > 解决方案 > 当类启动失败时,我可以返回 null 而不是对象吗?

问题描述

是否可以设计一个类构造函数来销毁对象或在启动失败时将其设置为 null。例如在下面的代码中 - 如果在数据库中找不到用户,那么将对象设置为 Null (A) 可能很有用......还是使用类成员标志$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"; }

标签: php

解决方案


您可以使用工厂模式(https://en.wikipedia.org/wiki/Factory_method_pattern)(或类似的东西)

<?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);

输出

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

推荐阅读