Autoloading classes in PHP - the PHP 5+ version

PHP

Please contribute by voting. Thanks!
3

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:
<?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:
<?php

#Autoload dependencies
spl_autoload_extensions(".php");
spl_autoload_register();

...
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

2
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

With:

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

Author

Created by Robert Bengtsson [126] Aug 1 '15

Share article

Do you know about

Startup?

Write an article