I just learned PHP has a GC based on reference counting. I thought, that is, RAII pattern can be adopted in PHP programming. Here's a proof of that concept:
<?php class Guard { private $callback; public function __construct(callable $callback) { $this->callback = $callback; } public function __destruct() { call_user_func($this->callback); } }
If you have the class above, then you can make PHP call the $callback
immediately after an object is destructed. Say, destruction is occurred when an object is free-ed by unset()
:
<?php require_once 'guard.php'; $guard = new Guard(function () { echo "unset!\n"; }); unset($guard); //=> unset!
PHP has function scope of variables. So, the Guard
class also works in the situation like bellow:
<?php require_once 'guard.php'; function foo() { $guard = new Guard(function () { echo "destructed!\n"; }); // ... do something ... } foo(); //=> echoed "destructed!" after function called
It's useful when you want to be assured some operation will be surely executed after dispatching a function; You can temporally set some global setting to local value (eg. time zone), execute chdir
to somewhere and affect nothing out of the function.