PHP 停止构造函数的最佳方法
PHP Best way to stop constructor
我正在处理停止构造函数的问题。
public function __construct()
{
$q = explode("?",$_SERVER['REQUEST_URI']);
$this->page = $q[0];
if (isset($q[1]))
$this->querystring = '?'.$q[1];
if ($this->page=='/login') {include_once($_SERVER['DOCUMENT_ROOT'].'/pages/login.php');
// I WANT TO EXIT CONSTRUCTOR HERE
}
stop/exit构造函数有函数:
die() , exit(), break() 和 return假
我使用的是 return false,但我对安全性感到困惑。退出构造函数的最佳方法是什么?
感谢您的宝贵时间。
一个完整的例子,因为问题应该有一个可接受的答案:
像这样在构造函数中抛出异常:
class SomeObject {
public function __construct( $allIsGoingWrong ) {
if( $allIsGoingWrong ) {
throw new Exception( "Oh no, all is going wrong! Abort!" );
}
}
}
然后当你创建对象时,像这样捕获错误:
try {
$object = new SomeObject(true);
// if you get here, all is fine and you can use $object
}
catch( Exception $e ) {
// if you get here, something went terribly wrong.
// also, $object is undefined because the object was not created
}
如果出于某种原因您没有在任何地方发现错误,它会导致致命异常导致整个页面崩溃,这将解释您 "failed to catch an exception" 并向您显示消息。
我正在处理停止构造函数的问题。
public function __construct()
{
$q = explode("?",$_SERVER['REQUEST_URI']);
$this->page = $q[0];
if (isset($q[1]))
$this->querystring = '?'.$q[1];
if ($this->page=='/login') {include_once($_SERVER['DOCUMENT_ROOT'].'/pages/login.php');
// I WANT TO EXIT CONSTRUCTOR HERE
}
stop/exit构造函数有函数:
die() , exit(), break() 和 return假
我使用的是 return false,但我对安全性感到困惑。退出构造函数的最佳方法是什么?
感谢您的宝贵时间。
一个完整的例子,因为问题应该有一个可接受的答案:
像这样在构造函数中抛出异常:
class SomeObject {
public function __construct( $allIsGoingWrong ) {
if( $allIsGoingWrong ) {
throw new Exception( "Oh no, all is going wrong! Abort!" );
}
}
}
然后当你创建对象时,像这样捕获错误:
try {
$object = new SomeObject(true);
// if you get here, all is fine and you can use $object
}
catch( Exception $e ) {
// if you get here, something went terribly wrong.
// also, $object is undefined because the object was not created
}
如果出于某种原因您没有在任何地方发现错误,它会导致致命异常导致整个页面崩溃,这将解释您 "failed to catch an exception" 并向您显示消息。