PHP如何扑捉未处理异常
class MyException extends Exception { function MyException($message, Exception $ex = NULL) { $this->message = $message; $this->innerException = $ex; } public $innerException = NULL; } function exception_handler($exception) { $s = '<pre>' . var_export($exception, true) . '</pre>'; $s = str_replace(" ", " ", $s); echo "<b style=\"color:red;\">Uncaught exception</b> " , $s, "\n"; error_log($s); // php.ini log_errors = On error_log = c:/php_errors.log display_errors = On } set_exception_handler('exception_handler'); //error handler function function customError($errno, $errstr, $errfile, $errline) { echo 'customError<br>'; throw new ErrorException($errstr, 0, $errno, $errfile, $errline); } //set error handler set_error_handler("customError"); function fnError($num, $div) { return $num / $div; } $fn = 'fnError'; //$i = $fn(123, 0); try { try { $i = 0; //throw new Exception("出错啦。"); } catch (Exception $e) { echo "错误扑捉1"; throw new MyException("自定义错误1", $e); } } catch (Exception $e) { echo "错误扑捉2"; throw new MyException("自定义错误2", $e); }
其他小技巧
清除缓冲区 ob_clean(); 清除之前所有的echo输出。
暂停3秒 sleep(3);
获取页面执行时长:
$running_time = time() - $_SERVER['REQUEST_TIME']; echo '页面运行时间:',$running_time,' 秒<br>';
PHP中的常量
define("D1", "dddd1"); class MyClass1 { const APP_NAME = "app"; } echo MyClass1::APP_NAME; echo D1; constant("D1"); constant("MyClass1::APP_NAME");
PHP的Session
session_start(); if ( isset($_SESSION['SID']) ) { echo $_SESSION['SID']; } $_SESSION["SID"] = "SESSION" . time(); //session_destroy(); //session_commit();
设置COOKIE setcookie("tt", "cookie");
输出变量内容
$s = var_export($_REQUEST, TRUE); echo "<pre>$s</pre>";