AndrewMcLagan
AndrewMcLagan

Reputation: 13987

Auto Class including and Instance creation PHP

Currently in an application i include classes from a directory (any number of classes could be dropped into this directory). Although i would like to go a step further and be able to create an array of class instances or class names CLASS from these files... is this possible when the class files are dropped into the folder? below is the code i currently use to include the files (php4 compat)

// Include custom field types, as drop-ins
$include_files = (array) glob( METAMAKER_FIELDS_DIR."*.php" );
if( is_array($include_files) ) {

    foreach($include_files as $filename) {
        if (!empty($filename) && strstr($filename, 'php')) {
            include_once($filename);
        }
    }
}

Upvotes: 0

Views: 848

Answers (3)

KingCrunch
KingCrunch

Reputation: 131871

Join us in the 21st century and use Autoloading. This is especially recommended, because with your approach its more complicated to ensure, that every dependency is resolved in the right order. Just don't do it this way.

Upvotes: 4

Neel Basu
Neel Basu

Reputation: 12904

If your Class name and file name are the same you can create a $className from $filename and create an instance and store it in $dict[md5($filename)] = new $className

However you are kind of re inventing autoload

Upvotes: 0

liquorvicar
liquorvicar

Reputation: 6106

If you're including the class files, you can use get_declared_classes() to get a list of class names. Constructing objects might be a little harder depending on what their constructors are like. If none of the constructors take (required) parameters, you could iterate through the list and construct one of each. Otherwise you may need to use reflection to work out what arguments you need to pass to each class.

You might want to ask yourself why you are doing this and whether you actually need one instance of each class. It sounds what you might need is some kind of Dependency Injection or Service Locator.

Upvotes: 0

Related Questions