unloco
unloco

Reputation: 7320

PHP7 produce error when array push is used on a string

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?

Upvotes: 1

Views: 605

Answers (1)

bubba
bubba

Reputation: 3847

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.

Upvotes: 2

Related Questions