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.

Thanks for help!

share|improve this question

feedback

1 Answer

up vote 7 down vote accepted

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);
share|improve this answer
There's a mistake in the function example: you call it Loader, but later call it as Load. – Maerlyn May 8 '11 at 21:47
mistake corrected ;) – peufeu May 8 '11 at 22:11
Thanks, I thought I could not set static variables within functions. – Gabriel Santos May 8 '11 at 22:28
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.