By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,128 Members | 1,228 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,128 IT Pros & Developers. It's quick & easy.

(OOP) object life time

Expert Mod 5K+
P: 8,639
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;
//more code
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?

Oct 19 '08 #1
Share this Question
Share on Google+
3 Replies

Expert 5K+
P: 5,058

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.
Oct 19 '08 #2

Expert Mod 5K+
P: 8,639
Thanks for the explanation, Atli. I was suspecting this, but haven't been sure.
Oct 19 '08 #3

Expert 5K+
P: 5,821
Heya, Dormilich.

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

Expand|Select|Wrap|Line Numbers
  1. class AnotherClass
  2. {
  3.   public function __destruct(  )
  4.   {
  5.     echo 'Destructor called!', PHP_EOL;
  6.   }
  7. }
  9. echo 'Calling mymethod().', PHP_EOL;
  10. $myclass->mymethod();
  11. echo 'mymethod() finished.', PHP_EOL;
You should see:

Expand|Select|Wrap|Line Numbers
  1. Calling mymethod().
  2. Destructor called!
  3. mymethod() finished.
Oct 19 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.