(OOP) object life time

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    (OOP) object life time

    recently I came over a piece of code where this question arose.
    scenarion: a new object is created locally in a class's method, but when will this object be destroyed? (ok, at latest at script end....)
    [PHP]class myclass
    {
    function mymethod() {
    $var = new AnotherClass;
    // more code, $var will not be manually (unset()) destroyed
    }
    }
    // now we use myclass to do something
    $globalvar = new myclass;
    $globalvar->mymethod();
    unset($globalva r);
    //more code
    [/PHP]
    what happens with (AnotherClass) $var? will it be destroyed when the method (mymethod()) is finished or when the container class (myclass) is destroyed? anyone an idea?

    thanks
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    #2
    Hi.

    As I understand it, all local variables will be destroyed when you leave the scope they belong to.

    In your case, all variables that belong to the "mymethod" method would be destroyed once the method has been executed. There is at least no point in keeping them around, as all references to them belong to a scope that is no longer in use and is not accessible by any other part of you code.

    Comment

    • Dormilich
      Recognized Expert Expert
      • Aug 2008
      • 8694

      #3
      Thanks for the explanation, Atli. I was suspecting this, but haven't been sure.

      Comment

      • pbmods
        Recognized Expert Expert
        • Apr 2007
        • 5821

        #4
        Heya, Dormilich.

        You can verify this by adding an echo to the object's destructor:

        [code=php]
        class AnotherClass
        {
        public function __destruct( )
        {
        echo 'Destructor called!', PHP_EOL;
        }
        }

        echo 'Calling mymethod().', PHP_EOL;
        $myclass->mymethod();
        echo 'mymethod() finished.', PHP_EOL;
        [/code]

        You should see:

        [code=text]
        Calling mymethod().
        Destructor called!
        mymethod() finished.
        [/code]

        Comment

        Working...