PHP

PHP Include All Files In A Folder

If you want to instantiate a class in PHP the class must be loaded into your application before you can use it. There are 4 ways you can load a class into your application include, include_once, require or require_once. But when you use this you must define all of the classes that you want to use in your application.

Another option is to use an autoload function which will be called when your application attempts to instantiate a class which isn't loaded.

<?php
function __autoload($classname) {
    $filename = $classname . ".php";

    if(file_exists( $filename ))
    {
        include_once($filename);
    }
}

$class = new MyClass();
$class2 = new OtherClass();
?>

Below is another solution you can use, but you must have all your files inside a folder of your application, you can then search a folder for all PHP files and include all these files in your application. This uses the PHP function glob() which will search for a pattern of file names and return them as an array. You can use this array to loop through the values and include the file, like the following code.

foreach (glob('folder/*.php') as $filename)
{
    include_once $filename;
}

new Class();
new ClassTwo();
new ClassThree();
Back to top ^

Join Paulund

  • Get access to 100s of premium tutorials and downloadable content
  • Members content consists of Premium WordPress plugins, CSS packages, jQuery packages, tutorial demo files and templates for 100s of web development tutorials
  • In-depth development tutorials
  • Priority tutorial requests
  • Priority email development support
  • No ads

Here at Paulund you'll find Web Development tutorials and snippets focusing mainly on PHP, WordPress and CSS. Members will get access to premium tutorials that go into more detail about development with these languages. You will also get access to downloadable premium content based on the tutorial.

Join Paulund

Leave a Reply

Your email address will not be published. Required fields are marked *