nfplee
nfplee

Reputation: 7977

PHP Autoload Catching new Exception

I have the following code defined to automatically include my classes:

spl_autoload_register(function($class) {
   require $class . '.php';
});

I then have a third party class (within the helpers namespace) with the following line:

throw new Exception('...');

The problem is that the autoload function tried to look for a file called helpers\Exception.php. I therefore changed my function above to:

spl_autoload_register(function($class) {
    if ($class != 'helpers\Exception') {
        require $class . '.php';
    }
}

But then it throws an exception saying the class helpers\Exception was not found. I'd appreciate it if someone could help show me how I can get it to simply display the original exception thrown in the third party class.

Upvotes: 0

Views: 329

Answers (2)

nfplee
nfplee

Reputation: 7977

I've managed to get this working. I had to add the following to the top of the class:

use Exception;

Another solution is to change:

throw new Exception('...');

to:

throw new \Exception('...');

But this solution requires changing every occurrence throughout.

Upvotes: 1

Tom
Tom

Reputation: 55

You need to escape the \ character. Try this: helpers\\Exception

Upvotes: 0

Related Questions