How to safely and dynamically create an instance of an existing PHP class?

Say I have a file Foo.php:\[code\]<?phpinterface ICommand{ function doSomething();}class Foo implements ICommand{ public function doSomething() { return "I'm Foo output"; }}?>\[/code\]If I want to create a class of type Foo I could use:\[code\]require_once("path/to/Foo.php") ;$bar = new Foo(); \[/code\]But say that I've created a Chain of Command Pattern and I have a configuration file that registers all the possible classes and creates an instance of these classes based on strings that are present in the configuration file. \[code\]register("Foo", "path/to/Foo.php");function register($className, $classPath){ require_once($classPath); //Error if the file isn't included, but lets //assume that the file "Foo.php" exists. $classInstance = new $className; //What happens here if the class Foo isn't //defined in the file "Foo.php"? $classInstance->doSomething(); //And what happens here if this code is executed at //all? //Etc...}\[/code\]How do I make sure that these classes are actually where the configuration file says they are? And what happens if a class isn't there (but the file is), will it create an instance of a dynamically generated class, that has no further description?
 
Back
Top