Q
Q
Quber2015-03-05 17:50:47
PHP
Quber, 2015-03-05 17:50:47

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);
}

Did not help :(

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Dmitry Entelis, 2015-03-05
@Quber

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.

V
Vladimir Balin, 2015-03-05
@krocos

Umm... Isn't __destruct()? It seems to be called when the object is destroyed, but if you call it explicitly...

M
Maxim Gavrilov, 2015-03-05
@thestump

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.

P
Pavel Volintsev, 2015-08-31
@copist

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 question

Ask a Question

731 491 924 answers to any question