0

How we load all classes that placed in different directory in one PHP File , means how to do auto load classes

Hardik Chapla
  • 435
  • 6
  • 26

2 Answers2

4

You can use ps4 and composer autoloader: https://getcomposer.org/doc/01-basic-usage.md#autoloading

composer.json:

{
    "autoload": {
        "psr-4": {"My_Name_Space\\": "My_Folder/"}
    }
}

Then run

composer dump-autoload
T. AKROUT
  • 1,719
  • 8
  • 18
2

You should name your classes so the underscore (_) translates to the directory separator (/). A few PHP frameworks do this, such as Zend and Kohana.

So, you name your class Model_Article and place the file in classes/model/article.php and then your autoload does...

function __autoload($class_name) 
{
    $filename = str_replace('_', DIRECTORY_SEPARATOR, strtolower($class_name)).'.php';

    $file = AP_SITE.$filename;

    if ( ! file_exists($file))
    {
        return FALSE;
    }
    include $file;
}

Example taken from Autoload classes from different folders

Edit#1 Not Tested

spl_autoload_register(function ($class_name) { 

     $filename = str_replace('_', DIRECTORY_SEPARATOR, strtolower($class_name)).'.php';

    $file = AP_SITE.$filename;

    if ( ! file_exists($file))
    {
        return FALSE;
    }
    include $file;
      }); 
Saad Suri
  • 1,352
  • 1
  • 14
  • 26