Autoloading classes in PHPUnit using Composer and autoload.php

Well, at first. You need to tell the autoloader where to find the php file for a class. That’s done by following the PSR-0 standard. The best way is to use namespaces. The autoloader searches for a Acme/Tests/ReturningTest.php file when you requested a Acme\Tests\ReturningTest class. There are some great namespace tutorials out there, just search … Read more

How to use spl_autoload() instead of __autoload()

You need to register autoload functions with spl_autoload_register. You need to provide a “callable”. The nicest way of doing this, from 5.3 onwards, is with an anonymous function: spl_autoload_register(function($class) { include ‘classes/’ . $class . ‘.class.php’; }); The principal advantage of this against __autoload is of course that you can call spl_autoload_register multiple times, whereas … Read more

How do I use PHP namespaces with autoload?

Class1 is not in the global scope. Note that this is an old answer and things have changed since the days where you couldn’t assume the support for spl_autoload_register() which was introduced in PHP 5.1 (now many years ago!). These days, you would likely be using Composer. Under the hood, this would be something along … Read more

What is Autoloading; How do you use spl_autoload, __autoload and spl_autoload_register?

spl_autoload_register() allows you to register multiple functions (or static methods from your own Autoload class) that PHP will put into a stack/queue and call sequentially when a “new Class” is declared. So for example: spl_autoload_register(‘myAutoloader’); function myAutoloader($className) { $path=”/path/to/class/”; include $path.$className.’.php’; } //————————————- $myClass = new MyClass(); In the example above, “MyClass” is the name … Read more