PHP 比较错误

我在学什么,在这个地球上的步行

PHP 比较错误

今天, 我在写一个脚本在 PHP 使用在命令行中,当遇到了意外的行为 (至少对我而言).
该脚本应接收三个参数, 其中最后一个包含一个或多个数字代码列表.
尝试验证此最后一个参数得到一个不同的结果,比想象中.
看到我正在使用的代码片段:

// test.php
if (php_sapi_name() = = 'cli') {
    $di = 设定($argv[1]) ? $argv[1] : 日期(' Y-m-' d); // Initial Date
    $df = isset($argv[2]) ? $argv[2] : 日期(' Y-m-' d); // Final Date
    $prods = isset($argv[3]) ? 爆炸(',', $argv[3]) : 数组(); // 代码列表

    ##### 验证
    // Initial Date
    if ($迪 != 日期(' Y-m-' d, strtotime($迪))) {
        回声 "\n";
        回声 "错误! 初始日期无效!\n";
        退出;
    }
    // Final Date
    if ($df != 日期(' Y-m-' d, strtotime($df))) {
        回声 "\n";
        回声 "错误! 无效的最后日期!\n";
        退出;    
    }

    // Codes
    if (计数($电棒) >; 0) {
        foreach ($作为 $prod 刺) {
            如果 ($产品 != (int)$产品) {
                回声 "\n";
                回声 "错误! 代码 " . $产品 . " 是无效的!\n" ;
                退出;
            }
        }
    }
    回声 "完成!";
}

有趣的是, 当我跑

# php-f test.php 2015-12-10 2015-12-11 33b

其结果是

# 完成

and reversing the condition to

        如果 ($刺激 = = (int)$产品)

显示预期的消息.
我试图将分配给单独的变量和仍然不工作.

            $检查 = (int) $产品;
            如果 ($产品 !$check =) {

为什么??

类型比较

!==

cannot be used here, 因为所有参数都将都是字符串. 当我虽然关于这我得到了答案.

So I did some command line tests and I check for the actually behavior of PHP Comparisons.

当我们做一样的事情:

$字符串 = = $integer

PHP will always do a CAST from String to the other type before comparison, 因此,代码

$字符串 = = (int) $字符串

will always return true, 自 $字符串 将更改为 int in both sides.

为了避免这种麻烦, is necessary to have the same type in both sides of comparison.

            $conf = (int) $产品;
            如果 ($产品 != (字符串) $conf) {
            // OR
            if ($产品 != (字符串)(int)$产品) {

见你.

 ;

留言

您的电子邮件地址将不会发布. 标记必填的字段 *

此网站使用 Akismet 减少垃圾邮件. 了解如何处理注释数据.