<?php namespace MyProject;
header("Content-Type: text/html; charset=utf-8");
error_reporting(0);
function theDataBaseObj()
{
$mysql = mysql_connect("localhost","roost","root","9096");
if($mysql){
return $mysql;
}else{
throw new Exception("Error Connect");
}
}
function db()
{
try{
$db = \MyProject\theDataBaseObj();
echo("success");
var_dump($db);
}catch(Exception $e){
echo("error");
var_dump($e->getMessage());
}
}
db();
?>
看陳小龍的PHP7實踐指南的時候遇到的這個問題,如果成功還無所謂,但是如果你連接數據庫失敗的話,問題就出現了,你會發錯誤碼255,頁面並不會打印出任何東西。
於是很糾結的去翻了翻blog ,文章。
stack overflow上有一個方案解決。
就是添加一下 use Exception
使用原生的Exception ,否則會出現Exception not found;
<?php namespace MyProject;
header("Content-Type: text/html; charset=utf-8");
use Exception;//看這裏,看這裏
error_reporting(0);
function theDataBaseObj()
{
$mysql = mysql_connect("localhost","roost","root","9096");
if($mysql){
return $mysql;
}else{
throw new Exception("Error Processing Request");
}
}
function db()
{
try{
$db = \MyProject\theDataBaseObj();
echo("success");
var_dump($db);
}catch(Exception $e){
echo("error");
var_dump($e->getMessage());
}
}
db();
?>