Answer the question
In order to leave comments, you need to log in
How to delete an object by calling some of its own methods (PHP)?
For example, there is an object that calls some of its function (method). It is necessary that after its call, the object becomes null. Then it is written to the database, and if it is null, then nothing is written. Actually I need to destroy it with my own function, how to do it?
PS I know how to do it with return null or return $this. But I need a void type method that doesn't return anything.
Thank you.
UPD
Tried like this:
public function test()
{
unset($this);
}
Answer the question
In order to leave comments, you need to log in
No way. As far as I know, in php you can't explicitly destroy an object at all. Just kill the link to it and, accordingly, wait for the garbage collector.
Umm... Isn't __destruct()? It seems to be called when the object is destroyed, but if you call it explicitly...
In order to completely destroy an object with its own function, there is no way, because in order to destroy it, it must be unloaded from memory, but so far its internal function has not worked out in any way. To destroy an object, it is necessary to complete the execution of all internal functions in the external function, nullify the reference to the object in a convenient way. As stated in the first answer, the garbage collector will come and free the memory. By calling unset($this) you destroy the pointer to its own object, but not the object itself.
In the object, provide a private flag property that will mean that this object is not stored.
<?php
class Dummy
{
/**
* Хранимый ли?
* @var boolean
*/
private $persistent = true;
public $me;
function __construct($me)
{
$this->me = $me;
}
public function forgetMe()
{
$this->persistent = false; // теперь нехранимый
}
/**
* Какая то логика при сохранении
*/
public function save()
{
if (!$this->persistent) // если нехранимый
{
echo $this->me . " was NOT saved\n";
return true; // понять, простить и забыть
}
echo $this->me . " saved OK\n";
}
}
$obj1 = new Dummy('first');
$obj2 = new Dummy('second');
$obj1->forgetMe();
$obj1->save(); // -> first was NOT saved
$obj2->save(); // -> second saved OK
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question