Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to declare destructor as private?

Tags:

oop

php

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.

like image 272
Desmond Hume Avatar asked Jan 30 '14 16:01

Desmond Hume


People also ask

Can we declare destructor in private?

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.

What happens if destructor is private in C++?

Private Destructor in C++ This code has private destructor, but it will not generate any error because no object is created.

Does a destructor need to be public?

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.

Should destructor be public C++?

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.


2 Answers

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.

like image 164
zzzzBov Avatar answered Sep 29 '22 18:09

zzzzBov


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.

like image 30
Manuel Bécares Avatar answered Sep 29 '22 16:09

Manuel Bécares