Bartek Kosa
Bartek Kosa

Reputation: 842

PHP - how to destroy object and objects it contains?

I have a CLI script written in PHP. In this script I have one instance of mainClass which contains a lot of instances of objects of other types which are stored in PHP arrays. How do I destroy $mainObject and all of the objects it contains?

EXAMPLE CODE:

class mainClass
{
    private $_array1 = array();
    private $_array2 = array();
    private $_array3 = array();

    public function __construct($data)
    {
        foreach ($data['a1'] as $val) {
            $this->_array1[] = new Object1($val);
        }
        foreach ($data['a2'] as $val) {
            $this->_array2[] = new Object2($val);
        }
        foreach ($data['a3'] as $val) {
            $this->_array3[] = new Object3($val);
        }
    }
}

$mainObject = new mainClass($data);

function someFunction(mainClass $mainObject)
{
    unset($mainObject);
}
  1. Does unset($mainObject) will destroy it and all objects it contains?
  2. Do I have to destroy every object separately?
  3. Should I use destructor of the mainClass to destroy objects (call theirs destructors) that $mainObject contains?

Upvotes: 2

Views: 6648

Answers (3)

Sanjay Kumar N S
Sanjay Kumar N S

Reputation: 4739

Best practice is to initialize that object to null.

$mainObject  = NULL;

Reference: What's better at freeing memory with PHP: unset() or $var = null

Upvotes: 4

Jasmin Patel
Jasmin Patel

Reputation: 36

unset($mainObject); Will destroy object and memory will be free.

Upvotes: 2

kailash sharma
kailash sharma

Reputation: 356

You're looking for unset().

But take into account that you can't explicitly destroy an object.

It will stay there, however if you unset the object and your script pushes PHP to the memory limits the objects not needed will be garbage collected. I would go with unset() (as opposed to setting it to null) as it seams to have better performance (not tested but documented on one of the comments from the PHP official manual).

That said do keep in mind that PHP always destroys the objects as soon as the page is served. So this should only be needed on really long loops and/or heavy intensive pages.

kindly refer this link

Best way to destroy PHP object?

Upvotes: 3

Related Questions