在类的构造函数中返回一个值 [英] Returning a value in constructor function of a class
问题描述
到目前为止,我有一个带有构造函数的 PHP
类
So far I have a PHP
class with the constructor
public function __construct ($identifier = NULL)
{
// Return me.
if ( $identifier != NULL )
{
$this->emailAddress = $identifier;
if ($this->loadUser() )
return $this;
else
{
// registered user requested , but not found !
return false;
}
}
loadUser
的功能是在数据库中查找特定的电子邮件地址.当我将标识符设置为某个电子邮件时,我确定它不在数据库中;第一个 IF 被通过,然后转到第一个 ELSE.这里构造函数应该返回 FALSE;相反,它返回一个包含所有 NULL 值的类对象!
the functionality of loadUser
is to look up the database for a particular email address.
When i set the identifier to some email that i'm sure it's not in the database; the first IF is get passed, and goes to the first ELSE. here the constructor should return FALSE; but instead, it returns an object of the class with all NULL values !
我如何防止这种情况发生?谢谢
how do i prevent this? thanks
谢谢大家的回答.那是相当快的!我看到 OOP 的方式是抛出一个异常.所以抛出一个,我的问题改变了我应该如何处理异常?php.net 的手册非常混乱!
thank you all for the answers. that was quite fast ! I see that the OOP way is to throw an Exception. So a throw one, my question changes that what should i do with the exception?? php.net's manual is pretty confusing !
// Setup the user ( we assume he is a user first. referees, admins are considered users too )
try { $him = new user ($_emailAddress);
} catch (Exception $e_u) {
// try the groups database
try { $him = new group ($_emailAddress);
} catch (Exception $e_g) {
// email address was not in any of them !!
}
}
推荐答案
构造函数不获取返回值;它们完全用于实例化类.
Constructors don't get return values; they serve entirely to instantiate the class.
在不重构您已经在做的事情的情况下,您可以考虑在此处使用异常.
Without restructuring what you are already doing, you may consider using an exception here.
public function __construct ($identifier = NULL)
{
$this->emailAddress = $identifier;
$this->loadUser();
}
private function loadUser ()
{
// try to load the user
if (/* not able to load user */) {
throw new Exception('Unable to load user using identifier: ' . $this->identifier);
}
}
现在,您可以以这种方式创建一个新用户.
Now, you can create a new user in this fashion.
try {
$user = new User('user@example.com');
} catch (Exception $e) {
// unable to create the user using that id, handle the exception
}
这篇关于在类的构造函数中返回一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!