I am dealing with stop the 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
}
There are function to stop/exit constructor :
die() , exit(), break() and return false
I am using return false but i am confusing about security. What is the best way to exit constructor ?
Thank you for your time.
Explanation. In PHP, the only rule to overriding constructors is that there are no rules! Constructors can be overridden with any signature. Their parameters can be changed freely and without consequence.
The constructor may be made private or protected to prevent it from being called externally. If so, only a static method will be able to instantiate the class. Because they are in the same class definition they have access to private methods, even if not of the same object instance.
PHP - The __construct FunctionA constructor allows you to initialize an object's properties upon creation of the object. If you create a __construct() function, PHP will automatically call this function when you create an object from a class. Notice that the construct function starts with two underscores (__)!
We can do this by using the special function call parent::__construct(). The "parent" part means "get the parent of this object, and use it", and the __construct() part means "call the construct function", of course. So the whole line means "get the parent of this object then call its constructor".
A full example, because questions should have an accepted answer:
Throw an 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 whatever reason you do not catch the error anywhere, it will result in a Fatal Exception that will crash the entire page, which will explain that you "failed to catch an exception" and will show you the message.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With