php PHP构造函数返回一个NULL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2214724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP constructor to return a NULL
提问by jaz303
I have this code. Is it possible for a Userobject constructor to somehow fail so that $this->LoggedUseris assigned a NULLvalue and the object is freed after constructor returns?
我有这个代码。User对象构造函数是否有可能以某种方式失败,以便为其$this->LoggedUser分配一个NULL值并在构造函数返回后释放该对象?
$this->LoggedUser = NULL;
if ($_SESSION['verbiste_user'] != false)
$this->LoggedUser = new User($_SESSION['verbiste_user']);
回答by jaz303
Assuming you're using PHP 5, you can throw an exception in the constructor:
假设您使用的是 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) {}
}
For clarity, you could wrap this in a static factory method:
为清楚起见,您可以将其包装在静态工厂方法中:
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']);
As an aside, some versions of PHP 4 allowed you to set $this to NULL inside the constructor but I don't think was ever officially sanctioned and the 'feature' was eventually removed.
顺便说一句,某些版本的 PHP 4 允许您在构造函数中将 $this 设置为 NULL,但我认为从未正式批准过,并且最终删除了“功能”。
回答by Pekka
AFAIK this can't be done, newwill always return an instance of the object.
AFAIK 这无法完成,new将始终返回对象的实例。
What I usually do to work around this is:
我通常做的解决这个问题是:
Adding a
->validboolean flag to the object that determines whether an object was successfully loaded or not. The constructor will then set the flagCreating a wrapper function that executes the
newcommand, returns the new object on success, or on failure destroys it and returnsfalse
向
->valid对象添加一个布尔标志,以确定对象是否成功加载。然后构造函数将设置标志创建一个执行
new命令的包装函数,成功时返回新对象,失败时将销毁它并返回false
-
——
function get_car($model)
{
$car = new Car($model);
if ($car->valid === true) return $car; else return false;
}
I'd be interested to hear about alternative approaches, but I don't know any.
我很想听听其他方法,但我不知道。
回答by Wim
Consider it this way. When you use new, you get a new object. Period. What you're doing is you have a function that searches for an existing user, and returns it when found. The best thing to express this is probably a static class function such as User::findUser(). This is also extensible to when you're deriving your classes from a base class.
这样考虑。当您使用 时new,您将获得一个新对象。时期。你正在做的是你有一个搜索现有用户的函数,并在找到时返回它。最好的表达方式可能是静态类函数,例如 User::findUser()。当您从基类派生类时,这也可以扩展。
回答by TheGrandWazoo
When a constructor fails for some unknown reason, it won't return a NULL value or FALSE but it throws an exception. As with everything with PHP5. If you don't handle the exception then the script will stop executing with an Uncaught Exception error.
当构造函数因某种未知原因失败时,它不会返回 NULL 值或 FALSE,但会引发异常。与 PHP5 的一切一样。如果您不处理异常,则脚本将停止执行,并显示未捕获的异常错误。
回答by TheGrandWazoo
A factory might be useful here:
工厂可能在这里有用:
class UserFactory
{
static public function create( $id )
{
return (
filter_var(
$id,
FILTER_VALIDATE_INT,
[ 'options' => [ 'min_range' => 1, ] ]
)
? new User( $id )
: null
);
}
}
回答by useless
maybe something like this:
也许是这样的:
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

