1

I have the following PHP Class:

class Init {

private static $instance = NULL;

public function __construct(){
}

public static function __callStatic($name, $arguments){

    if (is_null(self::$instance)) {
        $class = '\\' . __NAMESPACE__ . '\Drivers\\' . $name;

        $reflection = new \ReflectionClass($class);
        self::$instance = $reflection->newInstanceArgs($arguments);

        return self::$instance;
    } else {
        return self::$instance;
    }
}

}

Is there any other way to call the instantiated class, with the arguments array in that order, without using Reflection ? I've tried call_user_func_array() but it seems it doesn't work.

Thank you very much for your help

5
  • Is there a reason ReflectionClass is not ok while call_user_func_array is ok? Commented Nov 28, 2011 at 15:40
  • My class will be dependent to the ReflectionClass and i don't really know if that's ok. Commented Nov 28, 2011 at 15:57
  • Do you mean you might use it in PHP that doesn't support it? Otherwise it's exactly the same result as creating the instance normally Commented Nov 28, 2011 at 16:01
  • Do you mean you might use it in PHP that doesn't support it? Yes. Is that possible ? Commented Nov 28, 2011 at 16:14
  • No, it was introduced in php 5.1.3. Namespaces were introduced much later, in 5.3 I believe, so if you are using them in the first place... Commented Nov 28, 2011 at 16:28

1 Answer 1

0

You can try it like this:

public class Example{
    private static $instance;
    public static function singleton($arguments)
        {
            if (!isset(self::$instance)) {
                echo 'Creating new instance.';
                $className = __CLASS__;
                self::$instance = new $className($arguments);
            }
            return self::$instance;
        }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Please avoid using echo in a class. Instead use comments and exceptions where necessarily ;-)
If i use this, the instantiated class cunstruct will receive an only one argument. In the initiated class constructor i want to have something like this: __construct($name, $city, $etc){ }

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.