The early destructor run in the first test is an outcome of automatic garbage collection. To understand this, let's look at the second (easier) test:
1. $db = Mv_Core_Db_Manager::getInstance();
2. $sadb = $db->getStandaloneAdapter('bdm_bcb');
3. var_dump($sadb->getConnection());
Steps:
- the db manager is being assigned to the variable $db,
- the standalone adapter (MySQL adapter in this case due to hack in the factory you have introduced for debugging) is being assigned to $sadb,
var_dump()
debugs the return value of thegetConnection()
method of the $sadb standalone adapter, which is theresource(29, mysql link)
line in your second output,- clean up time; PHP garbage collector runs the destructor for $sadb (visible in your output thanks to debug) and after that $db (not visible in your output).
Here garbage collection is hapenning at the end.
If you consider the first test you have described, despite deceivingly similar looking source code, it has different steps:
1. $db = Mv_Core_Db_Manager::getInstance();
2. $sadb = $db->getStandaloneAdapter('bdm_bcb')->getConnection();
3. var_dump($sadb);
Steps:
- the same in the test case above,
- the return value of the
getConnection()
getter of the MySQL standalone adapter object is assigned to $sadb, - because the MySQL standalone adapter itself has not been assigned to any variable, PHP garbage collector decides that it's not used anymore so it cleans up the object and runs its destructor (the destructor debug is visible in your output in first),
var_dump()
debugs the value returned by the of thegetConnection()
getter of the MySQL standalone adapter, which is basically a handle to a resource which has already been collected by the garbage collector.
Here garbage collection happens before var_dump()
.
To summarize, the first test you have provided forces the garbage collector to jump in between lines 2 and 3 of your code. On the other hand, the second test forces the garbage collection at the very end.
The outcome is that your resource handle is pointing to memory that has been already cleaned up by the GC.