PHP7 produce error when array push is used on a string

末鹿安然 提交于 2019-12-11 04:57:07

问题


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

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

Is this possible?


回答1:


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

Results in:

Do not assign array item to a string

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.



来源:https://stackoverflow.com/questions/42390548/php7-produce-error-when-array-push-is-used-on-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!