Question

Im doing this

spl_autoload_register();

I have a folder called libs where all my files go like : user.php / orm.php etc and inside each class I have it like this

namespace libs;
class User { }

Calling the class like this

$app = new libs\User;

That seems to work but what should I do if for example I want to autoload a class that its not just inside libs folder, its for example inside :

libs / example / example.php

How should I autoload that class too?

Was it helpful?

Solution

Provided the class definition and namespace looks like this...

namespace libs\example;

class Example { ... }

The autoloader should be able to find it.

Note that the default spl_autoload lowercases the namespaces and class names so your file names and paths should all be lowercase (which you already appear to be doing but just thought I'd mention it).

Also note, for consistency, you should also set the appropriate autoload extensions, eg

spl_autoload_extensions('.php');
spl_autoload_register();

OTHER TIPS

As long as the namespaces are consistent, the default SPL autoloader will find it. Using your example, the class's name should be example, it should be in the libs\example namespace, and the file containing it should be libs/example/example.php.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top