rfc:counting_non_countables

This is an old revision of the document!


PHP RFC: Counting of non-countable objects

  • Version: 0.1
  • Date: 2016-10-04
  • Author: Craig Duncan git@duncanc.co.uk
  • Proposed PHP version: PHP 7.2
  • Status: Under Discussion

Introduction

Calling count() on an 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($val);
    }
}

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 raising a warning when attempting to count an object that doesn't implement Countable.

Backward Incompatible Changes

Counting objects that don't implement the Countable interface will still work, so the only BC will be in cases where userland convert warnings to Exceptions.

Proposed PHP Version(s)

PHP 7.2

Open Issues

  • Should we deprecate instead, and then disable in 8.0
  • Does introducing a warning in a minor release qualify as breaking BC

Unaffected PHP Functionality

Counting scalars is unaffected and will still return 1.

Proposed Voting Choices

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

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.1475573184.txt.gz · Last modified: 2017/09/22 13:28 (external edit)