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.
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.