Reputation: 12532
Well, I'm developing a framework and I'm working with __autoload
classes and exception
. The problem is that on PHP 5.2 you can't catch exceptions inside __autoload. I need catch them, there are some way to do it? PHP 5.3 it works fine!
On my framework, you have a folder that contains some classes, but the user can try load some class that not exists. The correct way is test if class_exists
, but I wan't make it optional, if user want work with exceptions. For instance:
$obj = new NotFoundClass();
In this example, if debug mode of framework is on, the client will be launched to an error page, explain about this problem (the class NotFoundClass is not found in class dir). Then only if user don't catch manually this problem, I'll launch to a internal error page, that tell client about this uncatched problem.
My current code is that, you can check full code on my github page or directly in the problematic file for better understanding. I don't know if I'm clear here, please talk to me in this case.
Upvotes: 1
Views: 145
Reputation: 197682
For the code in question:
$obj = new NotFoundClass();
you can do it the following:
function __autoload($className) {
$message = sprintf("Class '%s' not found.", $className);
if(version_compare(PHP_VERSION, '5.3.0') >= 0)
throw new Exception($message);
else{
eval("class $className {public function __construct() {
throw new Exception(\"$message\");
} }");
}
}
$obj = new NotFoundClass();
Which will make it throwing the exception regardless if it's PHP 5.2 or 5.3; Demo.
Upvotes: 1
Reputation: 29462
Short answer, from your question:
on PHP 5.2 you can't catch exceptions inside __autoload
The best you can do is to redirect user / do something with this error on your own, but not to let user decide what to do.
Example code to redirect user:
function missing_class_fatal_error_handler(){
global $missing_class;
header('Location: error_page.php?missing_class='.$missing_class);
}
function __autoload($class){
if(version_compare(PHP_VERSION, '5.3.0') >= 0)
throw new Exception("EXCEPTION: Class '$class' not found\n");
else{
global $missing_class;
$missing_class = $class;
register_shutdown_function('missing_class_fatal_error_handler');
}
}
try{
$x = new missingclass();
} catch (Exception $e){
echo $e->getMessage(); // PHP 5.3
}
echo "this will not execute under php < 5.3";
Upvotes: 2