dqbn76906 2012-01-16 16:20
浏览 43

无论操作数和运算符如何,PHP MySQL比较总是如此

For the record, I read documentation on boolean comparisons in PHP, but I do not understand how my code relates in this context. I thought I had a problem connecting to MySQL, but it turns out everything is fine and I can make queries without issue. So, MySQL is not really that relevant to this post.

I use this to report errors in an object that tried to connect on construction. Note that I tried ==, ===, != and !== only to get the same problem. I even tried casting the argument to bool and boolean.

Comments in below code blocks are relevant.

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());
        }
    }
}

Connecting is typical.

$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() says everything is ok, but assert() stops the presses no matter what.

I tried every operator and cast combination, even renaming the function out of paranoia over a name clash. Why does assert() only see true?

EDIT:

To make my problem clearer, consider the alternative implementation with Eugen's suggested use of is_resource. The problem is that I just have no idea why the below happens.

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 />";
    }
}

Output is out of order and the value changed after one comparison. Since I can make queries, $test must be true. I should not get output at all, but I do for every operator. I also tried it with FALSE replaced by 0.

Bad PHP instance?

1 !== false
=== false
!== false
!= false
  • 写回答

2条回答 默认 最新

  • duan0802 2012-01-16 16:27
    关注
    $this->assert(is_resource($this->con));
    
    评论

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据