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

问题描述 投票:0回答:2

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

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()exit()break()return false

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

感谢您的宝贵时间。

php security constructor exit
2个回答
15
投票

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

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

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
}

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


0
投票

如果你想退出构造函数而不实际上导致网站致命崩溃,而又不想捕获任何东西,那么你可以简单地

return
。您可能希望触发一个非致命错误,然后通过 return 存在


public function __construct()
{
   if ( $shit_is_wrong ) {

     trigger_error('Shit went wrong', E_USER_NOTICE);

     // in WordPress you should do this instead.
     wp_trigger_error(__METHOD__, 'Shit went wrong');

     return;
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.