I’ve encountered with a situation in which I need to call __destruct if a condition is true in __construct!
how to call destructor in constructor?
is there a way for that?
I can do this with a trick, but I need to do it inside my class, the goal is to destruct a class if does not meet my criteria.
EDIT :
In constructor I check for user permissions, If a user who is trying for deleting a post is someone other than admin, then the object of the class should not be instantiated, or in other word should be destructed.
Avoid doing actual work in your constructors. Constructors should essentially build an instance of the object. It doesn’t make sense to call
__destruct()from the constructor, because the instance is not owned by the method of the class, but by the function that called thenewoperator.Ask yourself what should be returned by the
newoperator at the call site in the case the object can’t be constructed?What should be assigned to
$objif the object cannot be properly constructed?NULL? Or perhaps the code doesn’t make sense at all?You have a few options:
Remove any non-construction code from the constructor, so that the constructor cannot fail at all. Put whatever code that fails in another method. Example:
If a failure in the constructor should be signaled to caller, use a static factory method that tests whether it is valid to instantiate the class, and returns either
nullor the new instance appropriately.If the code doesn’t make sense at all if the class cannot be constructed, perhaps you should throw an exception.