PHP经验分享程序猿的进阶屋

php7.1+版本的变量类型坑提示

2019-07-18  本文已影响2人  PHP的艺术编程

运行代码(留意$arr)

<?php
echo "PHP版本:" . phpversion();
$arr = "";
$arr2 = [];

function testArr(&$arr1) {
    $order['order_id'] = "222222aa";
    $arr1['order_id2'] = $order['order_id'];
}


testArr($arr);
testArr($arr2);

var_dump($arr,$arr2);

返回结果(PHP7.1之前版本代码)

PHP版本:7.0.33
array(1) { ["order_id2"]=> string(8) "222222aa" } array(1) { ["order_id2"]=> string(8) "222222aa" }

返回结果(PHP7.1+版本)

PHP版本:7.1.28
Warning: Illegal string offset 'order_id2' in /data/lab/5vbld3wy/index.php on line 8
string(1) "2" array(1) { ["order_id2"]=> string(8) "222222aa" }

结果对比

对比两个不同版本返回的结果。变量arr声明是一个空字符串,但是在函数中将arr当成数组使用。在7.1版本之前是不会有问题的,返回结果是数组;7.1版本之后,会报一个Warning,变量的类型还是按照之前声明的字符串类型

其他代码测试

代码1
<?php
echo "PHP版本:".phpversion();

$intVar = 100;

$stringVar = "php-test";

$arrVar = ['test' => php];

$boolVar = true;

var_dump($intVar = $stringVar);

var_dump($intVar = $arrVar);

var_dump($intVar = $boolVar);

var_dump($stringVar = $intVar);
返回结果1
PHP版本:5.6.40
Notice: Use of undefined constant php - assumed 'php' in /data/lab/5vbld3wy/index.php on line 8
string(8) "php-test" 
array(1) { ["test"]=> string(3) "php" } 
bool(true) 
bool(true)
PHP版本:7.1.28
Notice: Use of undefined constant php - assumed 'php' in /data/lab/5vbld3wy/index.php on line 8
string(8) "php-test" 
array(1) { ["test"]=> string(3) "php" } 
bool(true) 
bool(true)
PHP版本:7.3.4
Warning: Use of undefined constant php - assumed 'php' (this will throw an Error in a future version of PHP) in /data/lab/5vbld3wy/index.php on line 8
string(8) "php-test" 
array(1) { ["test"]=> string(3) "php" } 
bool(true) 
bool(true)
上一篇 下一篇

猜你喜欢

热点阅读