We may be able to generate a user warning using trigger_error () to make the program more flexible.
Index2.php
<? PHP
// PHP 4
require_once(
'cmd_php4/Command.php'
);
class
CommandManager
{
var
$cmdDir
=
"cmd_php4"
;
function
getCommandObject
(
$cmd
) {
$path
=
"{$this->cmdDir}/{$cmd}.php"
;
if (!
file_exists
(
$path
)) {
trigger_error
(
"Cannot find $path"
,
E_USER_ERROR
);
}
require_once
$path
;
if (!
class_exists
(
$cmd
)) {
trigger_error
(
"class $cmd does not exist"
,
E_USER_ERROR
);
}
$ret
= new
$cmd
();
if (!
is_a
(
$ret
,
'Command'
)) {
trigger_error
(
"$cmd is not a Command"
,
E_USER_ERROR
);
}
return
$ret
;
}
}
?>
If you use the trigger_error () function to replace die (), your code will be more advantageous in error handling and easier for client programmers to handle errors. Trigger_error () accepts an error message and a constant as the parameter. Constant:
Constant |
Description |
E_USER_ERROR |
A fatal error |
E_USER_WARNING
|
A non-fatal error |
E_USER_NOTICE
|
A report that may not represent an error |
You can design an error processor and then define a processor selection function set_error_handler () to use this error processor.
Second half of index2.php
<? PHP
// PHP 4
function
cmdErrorHandler
(
$errnum
,
$errmsg
,
$file
,
$lineno
) {
if(
$errnum
==
E_USER_ERROR
) {
print
"error: $errmsg/n"
;
print
"file: $file/n"
;
print
"line: $lineno/n"
;
exit();
}
}
$handler
=
set_error_handler
(
'cmdErrorHandler'
);
$mgr
= new
CommandManager
();
$cmd
=
$mgr
->
getCommandObject
(
'realcommand'
);
$cmd
->
execute
();
?>
Set_error_handler () accepts a function name as a parameter. If an error is triggered, the function in the parameter is called to handle the error. The function requires four parameters: Error mark, error message, error file, and number of lines in the error. You can also pass an array to set_error_handler (). The first element in the array must be the object that the error processor will call, and the second element is the name of the error handler function. We can see that our error processor is quite simple and can be improved. However, although you can add some features in the error processor, such as recording error information and outputting debug data, this is still a rough way to handle errors. Your choice is limited to errors that have been taken into account. For example, an e_user_error is captured. If you want to, you can stop the execution of the script (exit () and die () are not used, it may cause some subtle bugs, but the program that should have been suspended will continue to be executed.