PHP构造函数返回NULL

时间:2010-02-06 21:03:47

标签: php constructor error-handling null

我有这个代码。 User对象构造函数是否可能以某种方式失败,以便为$this->LoggedUser分配NULL值,并在构造函数返回后释放对象?

$this->LoggedUser = NULL;
if ($_SESSION['verbiste_user'] != false)
  $this->LoggedUser = new User($_SESSION['verbiste_user']);    

6 个答案:

答案 0 :(得分:64)

假设您使用的是PHP 5,则可以在构造函数中抛出异常:

class NotFoundException extends Exception {}

class User {
    public function __construct($id) {
        if (!$this->loadById($id)) {
             throw new NotFoundException();
        }
    }
}

$this->LoggedUser = NULL;
if ($_SESSION['verbiste_user'] != false) {
    try {
        $this->LoggedUser = new User($_SESSION['verbiste_user']);
    } catch (NotFoundException $e) {}
}

为清楚起见,您可以将其包装在静态工厂方法中:

class User {
    public static function load($id) {
        try {
            return new User($id);
        } catch (NotFoundException $unfe) {
            return null;
        }
    }
    // class body here...
}

$this->LoggedUser = NULL;
if ($_SESSION['verbiste_user'] != false)
    $this->LoggedUser = User::load($_SESSION['verbiste_user']);

顺便说一下,PHP 4的某些版本允许你在构造函数中将$ this设置为NULL,但我认为没有正式批准,并且最终删除了'feature'。

答案 1 :(得分:12)

AFAIK无法完成此操作,new将始终返回该对象的实例。

我通常要解决的问题是:

  • 向对象添加->valid布尔标志,以确定对象是否已成功加载。然后构造函数将设置标志

  • 创建执行new命令的包装函数,成功返回新对象,或者失败时将其销毁并返回false

-

function get_car($model)
      {
        $car = new Car($model);
        if ($car->valid === true) return $car; else return false;
     } 

我有兴趣了解其他方法,但我不知道。

答案 2 :(得分:5)

以这种方式考虑。使用new时,会得到一个新对象。期。你正在做的是你有一个搜索现有用户的函数,并在找到时返回它。表达这一点的最好的方法可能是静态类函数,例如User :: findUser()。当您从基类派生类时,这也是可扩展的。

答案 3 :(得分:4)

当构造函数由于某种未知原因而失败时,它不会返回NULL值或FALSE但会引发异常。与PHP5的一切一样。如果您不处理异常,那么脚本将停止执行Uncaught Exception错误。

答案 4 :(得分:4)

工厂在这里可能很有用:

class UserFactory
{
    static public function create( $id )
    {
        return (
            filter_var( 
                $id,
                FILTER_VALIDATE_INT, 
                [ 'options' => [ 'min_range' => 1, ] ]
            )
                ? new User( $id )
                : null
        );
  }
}

答案 5 :(得分:3)

可能是这样的:

class CantCreateException extends Exception{
}

class SomeClass {
    public function __construct() {
       if (something_bad_happens) {
          throw ( new CantCreateException());
       }
    }
}

try{
  $obj = new SomeClass();
}
catch(CantCreateException $e){
   $obj = null;
}
if($obj===null) echo "couldn't create object";
//jaz303 stole my idea an wrap it into a static method