Eric Lee Eric Lee - 5 months ago 10
PHP Question

why an object resets after execution? edited

I'm not new to programming but I found myself questioning how a function restart after execution. I was taught that every time a method start, the property or variable set while the method running resets.

If a function below in PHP executes, the property of the object set disappears.
How does it work?

class test{
private $prop1;

function test1($prop){

$prop1 = $prop;

$this->prop1 = $prop1;
}
}
$test = new test();
$test->test1("string");
echo $test->prop1;


As you can see the sample code above, it stores variable "$prop" at property "prop1".

But after execution, the property disappear and the variable $prop1 also disappear.

Can you explain the mechanism of this?

Or do i miss something very basic of programming?

Thanks in advance.

Answer

PHP uses a garbage collector. When a variable becomes unreachable, it is destroyed.

Regarding your code - the value of the $prop argument will not be destroyed after the method test1() finishes because you store it in the $prop1 property. $test->prop1 is still reachable after test1() exits (even if not directly).

class test
{
    private $prop1;

    function test1($prop)
    {
        $prop1 = $prop;

        $this->prop1 = $prop1;
    }
}

$test = new test();

$test->test1('hello');

var_dump($test);

Output:

object(test)#1 (1) {
  ["prop1":"test":private]=>
  string(5) "hello"
}
Comments