I have an class. I use one Object of this Class and want to stop class in its __construct
in some conditions like if user is not logged in. I have others codes after this object's line. I used die()
and exit()
functions, but these function stop whole of script. I just stop that class and echoes like please log in.
If you can assert in your constructor that your object can't be properly instantiated with the given parameter, you should throw an exception so that the rest of your program can be notified that the construction failed.
Of course, from there, you need to catch that exception and handle it accordingly in the section of your code that is trying to construct the object.
It could look like this:
class MyClass
{
public function __construct($user)
{
if(!$user->isLoggedIn())
{
throw new Exception('MyClass cannot be instantiated with a non-logged in user.');
}
/* .. rest of the constructor .. */
}
/* .. other methods .. */
}
Then in your script trying to construct an instance of MyClass
, you would need to have a try/catch as follows:
$user = getUser();
try {
$myObj = new MyClass($user);
}
catch(Exception $e) {
// Handle this case... $myObj = null; ?
}
/* ... rest of your script ... */
You might want to have a look at this page to decide what kind of exceptions you should throw and catch as you should avoid just throwing and catching an Exception
instance.