开发者

PHP OOP - Wrong object returned

开发者 https://www.devze.com 2023-03-04 16:56 出处:网络
with the follow code: <?php class Loader { private static $instances; function __construct($class = null) {

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消