Some of my classes declare their constructors as private because an object of such class is only allowed to be created by a static method of the class. May I also declare destructors of such classes as private to keep it symmetric, is it safe?
EDIT: Ok, seems like this is simply not possible:
Fatal error: Call to private AClass::__destruct() from context '' in /script on line 0
(the context is empty and there's no such thing as line 0). For some reason I used to think that the PHP runtime is almighty and can destruct anything it wants.
Private Destructor in C++ Destructors with the access modifier as private are known as Private Destructors. Whenever we want to prevent the destruction of an object, we can make the destructor private.
Private Destructor in C++ This code has private destructor, but it will not generate any error because no object is created.
If the destructor of a class Base is private, you can not use the type. If the destructor of a class Base is protected, you can only derive Derived from Base and use Derived.
It has no return type not even void. An object of a class with a Destructor cannot become a member of the union. A destructor should be declared in the public section of the class.
In php the __destruct
magic method must be public
. The method will automatically be called externally to the instance. Declaring __destruct
as protected
or private
will result in a warning and the magic method will not be called.
There's no symmetry necessary, as you should never explicitly call __destruct
.
Seems that you are implementing the singleton pattern. In this pattern constructor must be private and you have a static method that returns an instance of the class. If there's no instance, this static method will create it and return it.
If you set destructor access to private, you don't allow to other classes or functions to destruct that instance and this could be inconsistent if in a point of execution of your application you will not use that instance any more. There's no reason to set destructor to private because even if it's public, the static method is capable to return a new instance if there's no one.
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