What is the point of nulling private variables in a destructor?

I have the following template in the code I'm working with: in some classes in the destructor, I found that the private variable is null, in the example:

public function __destruct() { foreach($this->observers as $observer) { $observer = null; } $this->db_build = null; } 

Does it make sense to do this when PHP has a GC? Does this somehow improve script performance?

+4
source share
3 answers

This may be because PHP's garbage collection is based on reference counting , and older versions cannot handle circular dependencies. Then, in some cases, it would be necessary to manually set null references so that the GC can do its job, and there may be some special cases where the loop detection algorithm is not caught.

Most likely, this is just an example of religious cult programming (the Wikipedia entry even explicitly lists this as an example).

+2
source

This is sometimes just for the purity of the meme. But in your exmaple $observer and ->$db_build reference sub-objects. Thus, the goal is to destroy them before destroying the current object. (Although I'm not sure that the Zend core really likes to be interrupted when it is in a destructive rage. Maybe it has a spool list or something like that.)

In any case, this is not necessary from the point of view of the GC. But it would be reasonable if there was some dependence in the composite subprojects; e.g. counters or registers. Therefore, in most cases, it was not necessary to speak.

I made a stupid example to demonstrate the __destruct order:

 class dest { function __construct($name, $sub=NULL) { $this->name = $name; $this->sub = $sub; } function __destruct() { print "<destroying $this->name>\n"; $this->sub = NULL; print "</destroying $this->name>\n"; } } $d = new dest("first", new dest("second", new dest("third"))); exit; 

Without $this->sub = NULL , objects will be destroyed individually, not necessarily in the order they were created. With the removal of compound objects manually, however, PHP destroys three objects in a nested module:

 <destroying first> <destroying second> <destroying third> </destroying third> </destroying second> </destroying first> 
+3
source

first, a good programming tone, second, frees up script memory. if the script ends immediately after calling the PHP destructor, I don’t see any advantages.

0
source

Source: https://habr.com/ru/post/1332878/


All Articles