可能重复:
参考 - 这个符号在PHP中意味着什么?
我正在制作一个使用URL查询访问应用程序不同部分的Web应用程序.我正在寻找一个解决方案,使得无效的查询index.php?page=dashboarrrd显示错误404消息而不是PHP错误.
经过一番搜索后,我发现我可以使用以下内容来完成这项工作:
if(!@include($fileName)){
@include("pageData/404.php");
}
Run Code Online (Sandbox Code Playgroud)
这是有道理的,但我不知道为什么会有效.我的意思是,这到底是什么的@在之前include是什么意思?我完全理解,include $filename;但我需要一个解释@include ($fileName)
这是@错误控制操作符 (引用):
当在PHP中添加表达式时,将忽略该表达式可能生成的任何错误消息.
在正常情况下,如果include无法加载您作为参数传递的文件,它将发出警告.
预先设置@操作员include将防止该警告被发出 - 因此,显示/记录该警告.
那么,以下代码部分:
include 'does-not-exist.php';
Run Code Online (Sandbox Code Playgroud)
会得到以下警告:
Warning: include(does-not-exist.php) [function.include]: failed to open stream: No such file or directory
Warning: include() [function.include]: Failed opening 'does-not-exist.php' for inclusion
Run Code Online (Sandbox Code Playgroud)
虽然这一行:
@include 'does-not-exist.php';
Run Code Online (Sandbox Code Playgroud)
会让你不要警告.
并且,作为旁注,供参考:应该避免关闭操作员(@)的五个原因
你真正需要的代码是
$fileName = "pagedata/".basename($_GET['page']).".php";
if(is_readable($fileName)) {
include($fileName);
} else {
include("pagedata/404.php");
}
Run Code Online (Sandbox Code Playgroud)
和@在这里完全无关
@是缺乏经验的最大妄想之一.
使用它的人确实只期望一种错误,而实际上可能会有更多错误.并且禁止所有可能的消息来压制他们中的一个肯定是想把孩子和洗澡一起扔掉.
有一个根本问题会使这种误解如此普遍:
大多数PHP用户无法区分错误控制的三个方面:
大多数时候,为了[3],人们混淆了(1)和(2).虽然每个都需要单独处理:
is_readable()在我的代码中完全是为了那个. 404.php是这种用户友好行为的一个很好的例子.至于系统错误消息,用户根本不应该看到它们.只要display_errors关掉看看 - 再没有用@!| 归档时间: |
|
| 查看次数: |
11329 次 |
| 最近记录: |