我注意到,有一些功能,如is_int()
或isset()
或file_exists()
或functions_exists()
这在某种程度上是非常有用的.当我编写一些代码时,我总是会想到可能发生在我网站上的所有不好的事情,但有时候我遇到的问题包括:
等等,这个变量在PHP文件中设置; 这意味着没有人能够编辑它,对吗?如果这个"用户"可以编辑它,我会遇到很多麻烦,因为它可以管理PHP文件.
要么
这真的值得继续检查应该存在的文件吗?
让我们考虑下面的例子,它本身没有意义,但会帮助我让你理解我在说什么.PS:我故意夸大了代码.
config.php文件
$doActions = true;
Run Code Online (Sandbox Code Playgroud)
的functions.php
function getID() {
return $_COOKIE['userid'];
}
class eye {
public static function see() {
// gain the object the user is looking at
return $object;
}
}
Run Code Online (Sandbox Code Playgroud)
的index.php
class viewer {
private $poniesSeen = 0;
public function __construct() {
/* Magic ponies are created here */
}
public function sawAPony($id) {
if (file_exists('config.php')) {
if (isset($doActions)) {
if (is_bool($doActions)) {
if ($doActions) {
if (file_exists('functions.php')) {
if (function_exists('getID')) {
$id = getID();
if (!empty($id)) {
if (!is_int($id)) {
settype($id, 'int');
}
if (class_exists('eye')) {
if (method_exists('eye', 'see')) {
$o = eye::see();
if (is_string($o)) {
if ($o = 'pony') {
if (isset($this->poniesSeen) and is_int($this->poniesSeen)) {
++$this->poniesSeen;
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我想,应该保留哪些条件以及因为它们根本没有意义而抛弃的东西?我为什么不检查它们,我为什么要这样做?关于这种痴迷有没有一个黄金法则?
这就是语言带有错误消息(通常)的原因.如果出现问题,它不会只是默默地崩溃,它会告诉你.所以你可以对你认为应该永远是真实的东西做出合理的假设,如果由于某种原因它不是真的,你会被告知.
以下检查没用,IMO:
file_exists
- 如果文件名已知并且你把它放在那里.如果参数是变量,那么这是正常的.is_bool
,is_int
等等.如果你坚持的类型是正确的,使用===
比较.我曾经使用的唯一一个是is_array
.function_exists
等等 - 如果你知道文件在那里,并且你把函数放在文件中,你可以放心地假设函数存在.同样,有一些特殊情况,这个功能很有用 - 你的不是其中之一.isset
在某些情况下可能很有用,例如检查数组是否包含给定键的非null值,或者是否在$ _REQUEST中传递了参数.还有其他方法可以检查不涉及isset
,但这不是我的观点.
如果你可以合理地期望你的断言应该一直都是真的,那么你需要一个数据损坏或者很大的错误才能使它变错,不要费心去检查.如果在一百万次尝试中出现问题,那么您可以捕获错误并在下次修复它.否则,代码可读性的代价太高了.