0

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!

1 Answer 1

8

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);
Sign up to request clarification or add additional context in comments.

2 Comments

There's a mistake in the function example: you call it Loader, but later call it as Load.
Thanks, I thought I could not set static variables within functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.