rfc:counting_non_countables

This is an old revision of the document!


PHP RFC: Counting of non-countable objects

Introduction

Calling count() on a scalar or object that doesn't implement the Countable interface (http://php.net/manual/en/class.countable.php) returns 1. There are no known use cases for this, and it can easily hide bugs, take the following example:

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(), or handle_value(), or alert the developer to the issue.

Proposal

This RFC proposes adding a warning when calling count() with a parameter that is a scalar, null, or an object that doesn't implement Countable.

Note that the sizeof alias is also affected. http://php.net/manual/en/function.sizeof.php

Backward Incompatible Changes

The call to count() will still return 1 (or 0 for null) so backwards compatibility is maintained.

Environments that display warnings or convert them to more severe errors/exceptions would be affected, but this should just bring attention to a bug in the code.

Proposed PHP Version(s)

PHP 7.2

Proposed Voting Choices

Simple Yes/No vote that doesn't change the language itself so requires 50% + 1 votes to get 'accepted'.

Vote

Counting of non-countable objects
Real name Yes No
ajf (ajf)  
alan_k (alan_k)  
bishop (bishop)  
bwoebi (bwoebi)  
cmb (cmb)  
colinodell (colinodell)  
danack (danack)  
davey (davey)  
galvao (galvao)  
guilhermeblanco (guilhermeblanco)  
hywan (hywan)  
jhdxr (jhdxr)  
kguest (kguest)  
lcobucci (lcobucci)  
leigh (leigh)  
marcio (marcio)  
mariano (mariano)  
mbeccati (mbeccati)  
mfonda (mfonda)  
mike (mike)  
nikic (nikic)  
ocramius (ocramius)  
omars (omars)  
pierrick (pierrick)  
rasmus (rasmus)  
sammyk (sammyk)  
santiagolizardo (santiagolizardo)  
tpunt (tpunt)  
trowski (trowski)  
yohgaki (yohgaki)  
zimt (zimt)  
Final result: 31 0
This poll has been closed.

Patches and Tests

References

Initial discussion that led to this RFC's creation: https://github.com/php/php-src/pull/1672

rfc/counting_non_countables.1478301336.txt.gz · Last modified: 2017/09/22 13:28 (external edit)