11

How can I make PHPUnit respect __autoload functions?

For example, I have these three files:

loader.php

function __autoload($name)
{
    echo "foo\n";
    require_once("$name.php");
}

test.php

require_once("loader.php");

class FooTest extends PHPUnit_Framework_TestCase
{
    function testFoo()
    {
        new Foo();
    }
}

foo.php

require_once("loader.php");
new Foo();

As expected php foo.php errors out, saying that file "Foo.php" doesn't exist. The testFoo() function however errors out by saying that there is no such class as Foo, and never echos the "foo\n" line.

1
  • 1
    __autoload should work as long as you have php5... what version of php are you running? Commented Jul 7, 2011 at 14:44

3 Answers 3

23

This is expected behavior.

See this PHPUnit bugtracker entry: Upgrading to 3.5.10 has broken function of "autoload"

As of PHPUnit 3.5:

PHPUnit now uses an autoloader to load its classes. If the tested code requires an autoloader, use spl_autoload_register() to register it.

Quick fix:

The only change required is to add spl_autoload_register('__autoload') in your bootstrap script.

Longer fix:

If you can I'd suggest you just get rid of __autoload all together and use spl_autoload_register in your application as it is the way to go with PHP 5 code. (If you only have one autoloader you can't use the autoloader of your framework and so on)

Sign up to request clarification or add additional context in comments.

Comments

3

Try using spl_autoload_register instead of __autoload. spl_autoload_register allows for multipe autoloaders to work together without clobbering each other.

Comments

2

PHPUnit uses spl_autoload_register which turns off __autoload.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.