PHP Best way to stop constructor
I am dealing with constructor stopping.
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
}
There are functions to stop / terminate a constructor:
die () , exit () , break () and return false
I am using return false, but I am confused about security. What is the best way to exit the constructor?
Thank you for your time.
+3
source to share
1 answer
Complete example, because the questions should have an accepted answer:
Throw the exception in the constructor like this:
class SomeObject {
public function __construct( $allIsGoingWrong ) {
if( $allIsGoingWrong ) {
throw new Exception( "Oh no, all is going wrong! Abort!" );
}
}
}
Then, when you create the object, catch the error like this:
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
}
If for some reason you don't catch the error anywhere, it will result in a Fatal Exception, which will cause the entire page to crash, which will explain that you "couldn't catch the exception" and show you a message.
+5
source to share