Fatal error: Can not unset $ this PHP 7.1

4

I get the following error in PHP: Fatal error: Can not unset $ this that refers to this snippet of code:

public function __destruct(){
    unset($this);
}

That line I use to destroy an object, in previous versions of PHP it worked without problems but now with PHP 7 it shows me that error.

    
asked by Nilton Venegas 07.11.2017 в 23:09
source

1 answer

4

That error appears at least from PHP 7.

Anyway, keep in mind what the PHP Manual says about the method destruct :

  

PHP 5 introduces a concept of destructor similar to others   object-oriented languages, such as C ++. The destructive method   will be called as soon as there are no other references to an object   determined , or in any other circumstance of completion.

We can say that the destructive method is not stupid, he knows that when invoked is to destroy that object , so the use of $this is redundant. In PHP 7 they realized this and decided to launch this error message when unset($this) is invoked, because it really does not make sense to do so.

On the other hand, about destroying an object with unset the Manual says the following :

  

It is not possible to remove $this within a target object method   of PHP 5.

So how do I destroy an object?

In some cases, in PHP the object is destroyed when the script ends (there is no reference to the object). This is the case, for example, with the objects that connect to the database in PDO.

If you want to destroy the object explicitly, due to what is mentioned above, from PHP 5 the object will be destroyed as it happens in the other object-oriented languages: assigning null to the object.

$objMiObjeto=new MiObjecto();
    /*... uso del objeto*/
$objMiObjeto=null;

That's it, PHP takes care of the rest.

But what if the class does not have a destructive method written by me? Absolutely nothing happens ... this method is part of the so-called magic methods . Moreover, it is better that you do not try to write the destructive method. This post recommends never calling the destructive method explicitly ... the effect may be totally the opposite of what was expected.

    
answered by 07.11.2017 / 23:49
source