count() emitting an E_WARNING

后端 未结 3 1214
-上瘾入骨i
-上瘾入骨i 2020-12-09 20:13

Prior to PHP 7.2 using count() on a scalar value or non-countable object would return 1 or 0.

For example: https://3v4l.org/tGRDE



        
3条回答
  •  情歌与酒
    2020-12-09 20:17

    The problem is that calling count() on a scalar or object that doesn't implement the Countable interface returns 1, which can easily hide bugs.

    Given the following:

    function handle_records(iterable $iterable)
    {
        if (count($iterable) === 0) {
            return handle_empty();
        }
    
        foreach ($iterable as $value) {
            handle_value($value);
        }
    }
    

    Passing a Generator that yields nothing would not call handle_empty() nor handle_value().
    Also, no indication would be given that neither were called.

    By default, this will still return 1, though will additionally log a warning. If anything, this warning will bring attention to potential bugs in the code.

    See Counting Non-Countables for further information.

提交回复
热议问题