Click to See Complete Forum and Search --> : PHP Scope and dtor question


ninja9578
December 13th, 2010, 10:07 AM
I saw a coworker of mine doing something that I thought was strange and would like to make sure that what he's doing is safe.

He wrote a class like this:

class autolog {
public function __construct($method, $params){
MyLogger::Log('Entering ' . $method, $params);
$this -> mymethod = $method;
}
public function __destruct(){
MyLogger::Log('Exiting ' . $this -> mymethod);
}
public $mymethod;
};

Then it's being used like this:

public function foo ($params){
$log = new autolog(__METHOD__, $params);
... code ...
} //relying on autolog::__destruct getting called at this scope termination

This is a very common technique in C++ and other OOP languages, but I was always taught that you should NEVER use this type of technique with languages that manage their own memory because you have no guarantees of when the dtor gets called. I also know that PHP has no concept of what a C++ programmer would call scope.

Is it safe to rely on this behavior? Logs can be critical to get right.

PeejAvery
December 17th, 2010, 06:53 AM
I see nothing wrong with this. Remember that PHP, even though it is its own memory manager, it only reserves however much the configuration file allocates.

Also, it is a scripting language. So, when the script is finished its execution, the memory is released. Unless there are plans for an infinite loop, don't worry about it.