MikeBau
MikeBau

Reputation: 154

PHP, Is a copy of object created to be eliminated in some cases?

I have doubts as PHP objects behave after they have been deleted in some cases, doing some tests. Be the code:

class ItemRecord
{
    private $id;
    protected $name;

    public function __contruct($pID, $pName)
    {
        $this->id = $pID;
        $this->name = $pName;
    }
    public function setName($pName)
    {
        $this->name = $pName;
    }
    public function getName()
    {
        return $this->name;
    }
}

I Create some objects of the ItemRecord Class and then, append them to the object list (an Array):

$objList = array();

$obj1 = new ItemRecord("1", "Object 1");
$objList[] = $obj1;
$obj2 = new ItemRecord("2", "Object 2");
$objList[] = $obj2;

If I change some property in the 'original' object, for example:

$obj1->setName("FOO");

And then I'll try to show the content of the 'linked' element in the list with the original object:

echo($objList[0]->getName()); //-> Of course, It displays "FOO"

So if I delete the object should not exist in the list anymore

unset($obj1); unset($obj2);

But it's not like that!

echo($objList[0]->getName());

It continues displaying "FOO"!, and the object continues existing as well...

So my question is: In this case, when you delete an object, a copy operation occurs at delete time?

There are other curious cases like this strange behavior, but for now I will

UPDATED: After the answers and things have been talked in comments. Maybe it would be great if the unset() function could return the result of deleting. For example: 'true', if the var content or object could be finally removed.

Upvotes: 0

Views: 48

Answers (1)

ashishmaurya
ashishmaurya

Reputation: 1196

To answer your question : NO.

When you unset a value you are just removing a reference to that variable you are not actually deleting that. It will be deleted when there is no reference to that variable exits.

From PHP Documentation (http://php.net/manual/en/function.unset.php)

unset() destroys the specified variables

Upvotes: 2

Related Questions