PHP可以抛出错误而不是将字符串自动转换为数字吗?

时间:2013-11-20 14:48:36

标签: php implicit-conversion type-conversion

我正在编写应用程序的JavaScript和PHP,并且由于像$desc = $row[0] + " - " + $row[1];这样的拼写错误导致我显示为“0”的错误。

PHP是否有设置禁止自动将字符串转换为数字,所以我不会在最后一刻注意到这些错别字?

4 个答案:

答案 0 :(得分:2)

您可以牺牲一些性能来获得一致性并使用PHP的sprintf()sprintf.js

答案 1 :(得分:1)

+而不是.没有错,它只是不是你想要的。 如果你有这个问题,你总是可以使用自己的concat函数,比如:

<?php
function concatString(){
   $list = $arglist = func_get_args();
   $ret = "";
   for($i=0;$i<count($arglist);$i++){
     $ret .= $arglist[$i];
   }
   return $ret;
}
echo concatString("Test", "test2", $anotherVar);

答案 2 :(得分:0)

如果你想获得

,请使用$desc = $row[0] . " - " . $row[1];

答案 3 :(得分:0)

没有; PHP lovesautoconvert strings

<?php
$foo = 1 + "10.5";                // $foo is float (11.5)
$foo = 1 + "-1.3e3";              // $foo is float (-1299)
$foo = 1 + "bob-1.3e3";           // $foo is integer (1)
$foo = 1 + "bob3";                // $foo is integer (1)
$foo = 1 + "10 Small Pigs";       // $foo is integer (11)
$foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2)
$foo = "10.0 pigs " + 1;          // $foo is float (11)
$foo = "10.0 pigs " + 1.0;        // $foo is float (11)     
?>

作为commentedmanual code scanning可以检测出类似的荒谬案例,并且可以通过挂钩保存来实现自动化。 PHPLint on-line免费且易于使用:

PHPLint report

PHPLint 1.1_20130803
Copyright 2013 by icosaedro.it di Umberto Salsi
This is free software; see the license for copying conditions.
More info: http://www.icosaedro.it/phplint/


BEGIN parsing of test-p4Gx1L
1:      <?php
2:      $a = "Hi ";
3:      $b = "Bob";
4:      $c = $a + $b;

        $c = $a + $b;
                     \_ HERE
==== 4: ERROR: `EXPR + ...': expected number or array but found string

        $c = $a + $b;
                     \_ HERE
==== 4: ERROR: `... + EXPR': expected number or array but found string
5:      
6:      echo $c;
7:      ?>
END parsing of test-p4Gx1L
==== ?: notice: unused package `stdlib/dummy.php'
==== ?: notice: unused module `mysql'
==== ?: notice: unused module `pcre'
==== ?: notice: required module `standard'
Overall test results: 2 errors, 0 warnings.

与MySQL交谈仍然可以产生unexpected results