1

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?

unloco
  • 6,928
  • 2
  • 47
  • 58

1 Answers1

2

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.

Community
  • 1
  • 1
bubba
  • 3,839
  • 21
  • 25