Noam
Noam

Reputation: 3391

Deleting an object and creating a new one instead

I have a pointer to an object, which I want to release, and then create a new one. What I tried:

$this->myObject = null;
$this->myObject = new myObject($newVar);

Should this work? Am I doing it wrong? I tried calling __destructor() manually but that triggered an "unknown function" error.

Upvotes: 0

Views: 80

Answers (5)

Sean
Sean

Reputation: 696

To get what you want I think you have to pass by reference, not directly, otherwise variable b stores the value that was there at the time. Try: $a = new Foo(1); $a->bar = new Foo(2); $b = &$a->bar; $a->bar = new Foo(3);

Upvotes: 0

Álvaro González
Álvaro González

Reputation: 146430

As far as I know, there is no need to remove, unset or NULLify the property. The old object will be gone when you assign the new one if it isn't referenced anywhere else:

<?php

class Foo{
    public $id, $bar;
    public function __construct($id){
        $this->id = $id;
    }
}

$a = new Foo(1);
$a->bar = new Foo(2);
$a->bar = new Foo(3);

// No trace of Foo(2)
var_dump(get_defined_vars());

Compare with this:

class Foo{
    public $id, $bar;
    public function __construct($id){
        $this->id = $id;
    }
}

$a = new Foo(1);
$a->bar = new Foo(2);
$b = $a->bar;
$a->bar = new Foo(3);

// Foo(2) remains because it's still referenced by $b
var_dump(get_defined_vars());

Upvotes: 2

KingCrunch
KingCrunch

Reputation: 131871

First: PHP don't know any pointers, only references ;)

At all your solution should work. You overwrite the reference of $this->myObject with null. If there is no reference to the object, the object gets destroyed. You can omit the first step, because just overwriting ($this->myObject = new myObject($newVar);) is completely sufficient.

Just to note: If there are other references to that object, it will not get removed immediately, but the exact time an object gets destroyed is something, you should never take care about anyway. The garbage collector does a fine job :)

Upvotes: 0

patapizza
patapizza

Reputation: 2398

unset($this->myObject); $this->myObject = new Object($newVar);

should do the job.

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

PHP does not have pointers.

But, yes, this is fine. You don't need to set to null either; the original, now-dangling object will be garbage collected just like any other object.

Example:

<?php
class A {
   public function __construct() {
      echo "*A";
   }
   public function __destruct() {
      echo "~A";
   }
}

$o = new A;
$o = new A;

// Output: *A*A~A~A
?>

Upvotes: 4

Related Questions