问题
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