【发布时间】:2012-02-11 13:36:01
【问题描述】:
为了记录,我阅读了有关 PHP 中布尔比较的文档,但我不明白我的代码在这种情况下是如何关联的。我以为我在连接 MySQL 时遇到了问题,但事实证明一切都很好,我可以毫无问题地进行查询。所以,MySQL 与这篇文章并没有那么相关。
我使用它来报告试图在构造时连接的对象中的错误。请注意,我尝试了 ==、===、!= 和 !== 只是为了得到同样的问题。我什至尝试将参数转换为 bool 和 boolean。
以下代码块中的注释是相关的。
private function assert($test){ // Tried renaming in case PHP was funny about it.
if ($test === FALSE){ // Tried ==, ===, !== and != and casting $test.
if ($this->use_exception){
throw new mysql_exception();
}else{
die("MySQL ".mysql_errno()." - ".mysql_error());
}
}
}
连接是典型的。
$this->con = mysql_connect($host, $un, $pw, false, $ssl ? MYSQL_CLIENT_SSL : 0);
// I get 'yay'
echo mysql_ping($this->con) ? "yay" : "nay";
// This disagrees. Tried no cast, and a cast to bool.
$this->assert((boolean)($this->con != FALSE));
mysql_ping() 表示一切正常,但 assert() 无论如何都会停止印刷机。
我尝试了每个运算符和演员组合,甚至出于对名称冲突的偏执而重命名了函数。为什么 assert() 只看到 true?
编辑:
为了使我的问题更清楚,请考虑使用 Eugen 建议使用 is_resource 的替代实现。问题是我不知道为什么会发生以下情况。
private function assert($test){
$test = $test ? true : false;
if ($test === FALSE){
echo "$test === false<br />";
}
if ($test == FALSE){
echo "$test == false<br />";
}
if ($test !== FALSE){
echo "$test !== false<br />";
}
if ($test == FALSE){
echo "$test != false<br />";
}
}
输出无序,经过一次比较后值发生变化。因为我可以进行查询,所以 $test 必须为真。我根本不应该得到输出,但我为每个操作员做。我也试过用 0 代替 FALSE。
错误的 PHP 实例?
1 !== false
=== false
!== false
!= false
【问题讨论】:
-
你作为 $test 传递了什么?
-
你从
mysql_ping得到yay,这意味着$this->con实际上不是FALSE,这意味着$this->con != FALSE应该像它一样评估为true... -
那么问题出在哪里?正如我从您的帖子中了解到的那样,连接成功并且该函数返回一个链接标识符,它应该始终断言为 true .. L.E.:手册说“成功返回 MySQL 链接标识符,失败返回 FALSE。”所以我想你应该测试
if ($this->con === FALSE) -
@Mchl
$this->con != FALSE评估为true应该意味着($test === FALSE)评估为false,而不是“停止印刷机”,我怀疑OP的意思是“为什么只断言()见假”
标签: php mysql windows xampp boolean