I got confused with one thing about php autoloading stuff: the spl_autoload()
function. In every answer I found that this function is default implementation of __autoload
. Shouldn't PHP define default implementation of __autoload()
in itself and then if I explicitly create __autoload()
it will just override it?
If i don't explicitly define __autoload()
function in my php file, will be there the default implementation? Is spl_autoload()
some kind of internal function, if yes, why is it in php doc then?
(If it's not an internal function)In every spl_autoload() example there isn't any call to this function, only spl_autoload_register
with no parameters, spl_autoload_extensions
and so on. why so? What am I missing?
Quoting from: What is Autoloading; How do you use spl_autoload, __autoload and spl_autoload_register?
set_include_path(get_include_path().PATH_SEPARATOR.'path/to/my/directory/'); spl_autoload_extensions('.php, .inc'); spl_autoload_register();
Since spl_autoload is the default implementation of the __autoload() magic method, PHP will call spl_autoload when you try and instantiate a new class.
So if I won't call spl_autoload_register()
, it won't register the default implementation? Does the spl_autoload
look into extensions set by spl_autoload_extensions();
and then import all files with these extensions from include path? Repeating question mentioned earlier: is spl_autoload()
internal function?
I know that __autoload()
is deprecated and I should use spl_autoload_register()
. I just want to make sure that I know how it all works.
Thanks.
Repeating question mentioned earlier: is
spl_autoload()
internal function?
That's just the "default value" for spl_autoload_register
if you don't pass an parameter. You could also call this function standalone, if you want to. The behaviour of spl_autoload could be configured with spl_autoload_extensions
and set_include_path
.
Internally spl_autoload
takes the full qualified class name(fqcn) as the path to look for a class implementation. (Maybe with string replacements for directory seperators). Afterwards, it searches in every element of the class_include_path after the given file.
spl_autoload_extensions(".php");
spl_autoload_register();
$foo = new \foo\Bar();
// now spl_autoload tries to load the file foo/Bar.php inside your class path.
If you need something more complicated, you have to create your own callback for the autoloader. I.e. something like this
spl_autoload_register(function($class) {
$path = 'classes' . DIRECTORY_SEPERATOR;
// dont care about case
$class = strtolower($class);
// replace _ with DIRECTORY_SEPERATOR
$name = str_replace('_', DIRECTORY_SEPERATOR, $class);
// don't care about windows/unix
$name = str_replace('/', DIRECTORY_SEPERATOR, $name);
$file = $path . $name . '.php';
if (file_exists($file)) {
include ($file);
}
});
Note: The example above doesn't care about the value of spl_autoload_extensions
or set_include_path
.