Say I have a file Foo.php:
<?php
interface ICommand
{
function doSomething();
}
class Foo implements ICommand
{
public function doSomething()
{
return "I'm Foo output";
}
}
?>
If I want to create a class of type Foo I could use:
require_once("path/to/Foo.php") ;
$bar = new Foo();
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.
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...
}
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?
You can use class_exists to check if a class has been defined.
If you are calling a class dynamically and also calling a method on that class from within the same function, you may also wish to call that method dynamically (unless all of your classes have the exact same method. If that is the case, you can also use method_exists
Finally, you can also use file_exists to ensure the file can be included: