Web lists-archives.com

Re: Updating legacy code ...

On 04.03.2019 at 19:59, Lester Caine wrote:

> We are told that '@' will be dropped at some point? But perhaps it IS
> the right solution to fix what simply looks like a mistake anyway.

count() raises this warning due to
<https://wiki.php.net/rfc/counting_non_countables>.  I wouldn't call
this change a mistake, but rather that count() did accept arbitrary
values without at least raising a warning, since the result for
non-countable values is somewhat arbitrary, and passing a non-countable
value to count() may not even be intended.

> What I AM trying to establish is just what is the 'correct' way to do
> these things since it is obvious that the methods used for 20+ years are
> no longer acceptable? @ may work as a fix today, but for PHP8?

It seems to me the simplest clean fix for your case would be to define
your own count() that behaves the way your code expects, e.g.

  function my_count($value)
      if (is_array($value) || $value instance of Countable) {
          return count($value);
      } elseif (is_null($value)) {
          return 0;
      } else {
          return 1;

and then use your counting function instead of the built-in count().  As
of PHP 7.3.0, there is is_countable()[1] which helps to simplify the
example code above.

[1] <https://wiki.php.net/rfc/is-countable>

Christoph M. Becker