How we load all classes that placed in different directory in one PHP File , means how to do auto load classes
Asked
Active
Viewed 836 times
0
-
This is already extensively documented [in PHP's docs](http://php.net/manual/en/language.oop5.autoload.php). – May 31 '17 at 10:26
-
How is this related to CSS? – Gerard May 31 '17 at 10:39
2 Answers
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
-
1
-
-
1Yes you can use simply the function spl_autoload_register() to autoload classes – T. AKROUT May 31 '17 at 10:45
-
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
-
-
1Also note you can use spl_autoload_register() to make any function an autoloading function. It is also more flexible, allowing you to define multiple autoload type functions. Please refer to the link – Saad Suri May 31 '17 at 10:41
-
-
1