PHP OOP - Wrong object returned
with the follow code:
<?php
class Loader {
private static $instances;
function __construct($class = null) {
return self::instance($class);
}
public static function instance($class) {
if(!isset(self::$instances[$class])) {
self::$instances[$class] = new $class();
}
return self::$instances[$class];
}
}
class Core {
}
$core = new Loader('Core');
print_r($core);
?>
my print_r() return the object Loader instead the object Core, which is instantiated after Loader is constructe开发者_运维百科d.
Thanks for help!
Hm ?
If you do
$core = new Loader('Core');
Then $core is going to be an instance of Loader... PS : constructors don't return a value.
You don't need to instantiate Loader at all.
Do this :
<?php
class Loader {
private static $instances;
public static function instance($class) {
if(!isset(self::$instances[$class])) {
self::$instances[$class] = new $class();
}
return self::$instances[$class];
}
}
class Core {
}
$core = Loader::instance('Core');
print_r($core);
Or you could do a much simpler :
<?php
function Load($class)
{
static $instances;
if(!isset($instances[$class]))
$instances[$class] = new $class();
return $instances[$class];
}
class Core {
}
$core = Load('Core');
print_r($core);
精彩评论