Functions are amazing. Working with huge function files is not.
I like to group all my functions into different “function files” to keep everything nice and clean. For example, I’ll keep all my functions that clean up various strings or elements in a clean.php file.
This is great because I don’t have to scan a 50000 line PHP file to find the function that I’m looking for.
As your application grows, the number of function files may grow with it. This can pose a problem. Did you remember to include the new function file in all necessary scripts?
This is where this little beauty piece of code comes in.
I like to keep this in my init.php file that runs before any pieceĀ of code in my script. This insures that it’s included in EVERY PHP script I use.
//include all the files in the functions folder
//MAIN_PATH is a variable that i've set to the main path of my script
foreach (glob(MAIN_PATH."/inc/php/functions/*.php") as $filename) {
include_once($filename);
}
What’s going on here? Basically we are looping through every file that is included in the inc/php/functions folder and included it in our script.
Everytime the script runs it checks for new files.
Never again will you have to worry that a function file was not included in your script.

Jason Robb
10/05/09 @ 12:10 pm
Hot! Thank you. This is definitely going to help. Saving this to my Coda Clips now.
Cheers,
Jason R.
Matt Vickers
10/05/09 @ 04:10 pm
Gotta love the coda tips. I’m thinking of releasing a pack when my clips become worthwhile (read: more than 2).
Julius Beckmann
10/05/09 @ 01:10 pm
Hi,
i can see a problem i would run into when using this code. I tend to create multiple files with different versions of a function/class. That might become unhandy when always including everything. And changing .php to .php.something is not ok.
But i have a speedup idea for that code. I would not use this lines on my productive sites. Cause is the glob() function that needs to do unnecessary STAT calls every time. It would be much more performant if we could cache the list of files with APC or similar.
My example code:
// Fetch functions file list from cache
$file_list = apc_fetch(‘mysite_files_functions’);
if(!$file_list) {
$file_list = glob(MAIN_PATH.”/inc/php/functions/*.php”);
if($file_list)
// Cache for 60 seconds
apc_store(‘mysite_files_functions’, $file_list, 60);
else
$file_list = array();
}
foreach($file_list as $filename) {
include_once($filename);
}
Regards, Julius
Matt Vickers
10/05/09 @ 04:10 pm
Thanks for the tip, I’m always looking to improve anything I write. I will look into this!