PHP – Including All Files in a Directory

Posted (Updated ) in PHP

Including every file in a specific directory automatically is a useful way of auto-loading classes in PHP. This could be done manually of course but we’re developers and we’re lazy so here’s a better solution utilizing PHP’s glob() function:

	foreach( glob(dirname(__FILE__) . '/classes/*.php') as $class_path )
		require_once( $class_path );

In this script, glob() searches for all pathnames matching the given pattern (In this case all files with a .php extension in the ‘classes/’ directory). Please note that if glob() doesn’t find any matches it will return false instead of the expected array, so unless you’re iterating over its results with a function that checks for this – such as foreach – either typecast or perform some other form of validation before use. You’ve been warned.

UPDATE 15 May 2010: Found this informative article related to the various ways of loading all files in a directory and their respective speeds – performance matters, people!.