Autoloading classes in PHP - the PHP 5+ version


Please contribute by voting. Thanks!

If you are working with object oriented programming in php (which you definitely should) this is probably the easies way of autoloading your classes:

1. Only have one class per file

2. Name the files exactly as your classes are named

E.g. class customer goes into file customer.php:

namespace entities;

class customer


3. Use directory structure namespaces

Namespaces must follow your directory structure, e.g.

Classes in directory /services/repositories/ have the following namespace:
namespace services\repositories;

4. Register automatic class autoloading

Place this first in your index.php file:

#Autoload dependencies

All you have to do now is to call your classes by name and it will work without you having to include all the directories, eg:
$customerrepository = new services\repositories\customerrepository();
You can use either the fully-qualified class name when refering to the class or use the use-statement to specify which class you are refering to.

Article created: Aug 1 '15. Edited Aug 14 '15.

1 Comment

Christoffer [2]  •  Aug 3 '15  •   •  Reply

This spl_autoload_extensions(".php"); is not needed, but it makes it load alot faster.

Without spl_autoload_extensions(".php");

1000 requests (with ab -n 1000 -c 5) 8.8s 8.8s 8.9s

99% requests served in: 56ms 100% requests served in 61ms


7.3s 7.5s 7.3s

99% requests served in: 49ms 100% requests served in 52ms

Custom spl_autoload_register method:

7.9s 7.8s 7.8s

99% requests served in: 50ms 100% requests served in 55ms

So DON'T forget to register the php extension.

Your comment

You need to sign up / log in to comment this article


Created by Robert Bengtsson [126] Aug 1 '15

Share article

Do you know about


Write an article