开发者

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->myOb开发者_开发问答ject = new myObject($newVar);

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


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
?>


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


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

should do the job.


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 :)


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜