[英]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 constructed. 我的print_r()返回对象Loader而不是对象Core,该对象在构造Loader之后实例化。
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. 然后$ core将成为Loader的实例... PS:构造函数不返回任何值。
You don't need to instantiate Loader at all. 您根本不需要实例化Loader。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.