返回类的构造函数中的值 [英] 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 !!
}
}
推荐答案
不获得返回值;
没有重组你已经在做的事情,你可以考虑在这里使用一个异常。
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屋!