PHP停止构造函数的最佳方法

时间:2015-01-02 12:54:56

标签: php security constructor exit

我正在处理停止构造函数。

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
}

有停止/退出构造函数的函数:

die()退出() break()返回false

我正在使用return false,但我对安全性感到困惑。退出构造函数的最佳方法是什么?

感谢您的时间。

1 个答案:

答案 0 :(得分:7)

一个完整的例子,因为问题应该有一个可接受的答案:

在构造函数中抛出异常,如下所示:

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
}

如果由于某种原因你没有在任何地方发现错误,它将导致致命异常,这将导致整个页面崩溃,这将解释你“未能捕获异常”并将向您显示消息。

相关问题