I came a cross this line of code in Codeigniter HMVC extension (by Wiredesignz), where a class got instantiated without getting assigned to a variable (class CI in Base.php)
The code :
class CI extends CI_Controller
{
public static $APP;
public function __construct() {
/* assign the application instance */
self::$APP = $this;
global $LANG, $CFG;
/* re-assign language and config for modules */
if ( ! is_a($LANG, 'MX_Lang')) $LANG = new MX_Lang;
if ( ! is_a($CFG, 'MX_Config')) $CFG = new MX_Config;
parent::__construct();
}
}
/* create the application object */
new CI;
What's the name of this technique? What's the implication?
This has not a name and the implication is, that the constructor is definitely doing too much. The reason one wants to create an instance of a class without referencing it is, that he only wants the constructor wants to be executed, but nothing more. This means, that the constructor "does" something, but a constructor should only ensure, that an object is in a stable/valid state and nothing more.
In short: Don't assume that this is a good practice. The global
and self::$APP = $this
confirms my opinion that this is a bad piece of code.
I guess this could be seen as some sort of facade design
. -The Class(constructor is called) and assignment is done, albeit in the constructor itself.
so new CI
is just extending the Super object and initializing its own constructor. Similar to a function, function somefun(){ return }; somefunc();//call somefunc
CI_Controller loads all of the classes required to run Codeigniter, it is the SUPER object
$ci = &get_instance() // CI_Controller