在字符串上使用数组推送时,PHP7产生错误 [英] PHP7 produce error when array push is used on a string

查看:90
本文介绍了在字符串上使用数组推送时,PHP7产生错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当将项目推入字符串时,如何配置PHP 7以产生错误,例如:

How can I configure PHP 7 to produce an error when an item is pushed to a string, for example:

$items = '';
$items[] = 'test';

这可能吗?

推荐答案

在PHP 5.6和7.0中,将包含空字符串的变量转换成这样的数组是有效的.因此,您将需要提供自己的验证以产生异常.

In PHP 5.6 and 7.0, it is valid to convert a variable containing an empty string into an array like this. Therefore, you will need to provide your own validation to produce an exception.

function checkAndAssign($var, $val){
    if (is_string($var)){
        throw new ErrorException('Do not assign array item to a string');
    }
    return $val;
}

$items = '';

try{
    $items[] = checkAndAssign($items, 'test');
}catch(Exception $e){
    echo $e->getMessage();
    return;
}

var_dump($items);

结果:

请勿将数组项分配给字符串

Do not assign array item to a string

在PHP 7.1中,这将产生致命错误.问题如何捕获致命的PHP问题已经有了很好的答案错误,如果您想尝试.

In PHP 7.1 this generates a Fatal Error. There is already a good answer to the question How do I catch a PHP Fatal Error if you want to attempt that.

这篇关于在字符串上使用数组推送时,PHP7产生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆