Jump to content

spl_autoload_register and class upper/lower case


NotionCommotion

Recommended Posts

I mostly if not always name my classes with the first letter capitalized.

 

I typically use enable autoloading as follows.  I don't know when I started converting the class name to under-case.  As such, however, I need to make the filenames undercase.

 

Is this the correct approach?

spl_autoload_register(function ($class) {
    $class=strtolower($class);
    if(file_exists(__DIR__.DIRECTORY_SEPARATOR.'classes'.DIRECTORY_SEPARATOR.$class.'.php')) {
        require_once __DIR__.DIRECTORY_SEPARATOR.'classes'.DIRECTORY_SEPARATOR.$class.'.php';
    }
});

 

Unrestricted file inclusion is never a good idea. You seem to think that $class is only the actual class name, but it contains the complete class path including namespaces, e. g. “Foo\Bar”. Since the backslash also happens to be a directory separator on Windows, you may end up including files that were never intended for that. You're lucky that PHP currently doesn't support relative namespaces, because then you might end up with something like

..\your_config_file_with_the_app_passwords

Always restrict file inclusions, don't just append the input to some path. Think about how you want to handle namespaces, otherwise restrict the names to a-zA-Z or something like that.

 

This DIRECTORY_SEPARATOR stuff is unnecessary, just use forward slashes. That's what all operating systems except Windows use, and even Windows accepts slashes.

 

Last but not least, strtolower() is likely to cause trouble if you use any characters outside of the ASCII range (like umlauts). Yes, that's permitted in class names.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.