Chris
Chris

Reputation: 8432

Instantiating classes with params in singleton factory

I have a class that produces singleton classes. (Note that this is overly simplified code for the purpose of this question, for example it doesn't check that the filepath exists)

class Singleton
{
   public function Load($classname, $params)
   {
      $filepath = 'classes/'.$classname.'.php';
      require_once($filepath);
      return $classname();
   }

}

Now say that I wanted to pass an array of parameters that can vary in size to the constructor of the class being created. What is the best way to do this? I envision something along the lines of call_user_func_array but for classes?

Upvotes: 1

Views: 2294

Answers (2)

Mike S
Mike S

Reputation: 419

You can achieve some interesting results with the use of PHP's Reflection library.

function Load( $class, $args )
{
    $reflection = new ReflectionClass( $class );
    $object = $reflection->newInstanceArgs( $args );
    return $object;
}

This is simplified and implies use of the __autoload function, nor does it check for namespaces if you use them, plus it'll create a new instance of the class every time you call it, so you'll need to implement an array of objects to keep track of which ones you've created already, etc...

And for basic documentation: $class is a string with the name of the class you're wishing to instantiate, and $args is an array of arguments that you'll pass to the __construct( ) method.

Upvotes: 2

Jorg
Jorg

Reputation: 7250

not tested, but why not just load them into the constructor? ie return $classname($params); with your constructor set up like __construct($params = false). You can then check if params is passed or not, making your constructor parameters optional...

This does mean all your classes need to have the same constructor though.

    class Foo {

        public function __construct($params = false) {
            if($params === false) 
                echo 'not passed';
            else 
                print_r($params);
        }
    }

$class = 'Foo';
$foo = new $class(array('one', 'two'));
$foo2 = new $class();

outputs: Array ( [0] => one [1] => two ) not passed

Upvotes: 0

Related Questions