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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.