cosmorogers
cosmorogers

Reputation: 453

PHP: Count an ArrayAccess object without Countable

So I'm working with some external PHP code that I don't have the full source for. I am using reflection to work out callable methods, etc.

They have a class like so:

class SpecialArray implments \ArrayAccess
{
    public function offsetExists($index){}
    public function offsetGet($index){}
    public function offsetSet($index, $value){}
    public function offsetUnset($index){}
}

So logically I can foreach(SpecialArray), that's fine.

However in the code I can somehow do count(SpecialArray) and get the correct count, eg if there are 5 elements in the SpecialArray doing count(SpecialArray) will return 5!

However there isn't a count method in the class, nor does the class implement Countable Calling SpecialArray->count() also fails with Call to undefined method

Does anyone have any ideas how they may be doing this voodoo magic??

Full \ReflectionClass::export()

Class [  class ThirdParty\SpecialArray implements ArrayAccess ] {

  - Constants [0] {
  }

  - Static properties [1] {
    Property [ public static $_metadata ]
  }

  - Static methods [1] {
    Method [  static public method &getMetadata ] {

      - Parameters [0] {
      }
    }
  }

  - Properties [0] {
  }

  - Methods [5] {
    Method [  public method offsetExists ] {

      - Parameters [1] {
        Parameter #0 [  $index ]
      }
    }

    Method [  public method offsetGet ] {

      - Parameters [1] {
        Parameter #0 [  $index ]
      }
    }

    Method [  public method offsetSet ] {

      - Parameters [2] {
        Parameter #0 [  $index ]
        Parameter #1 [  $value ]
      }
    }

    Method [  public method offsetUnset ] {

      - Parameters [1] {
        Parameter #0 [  $index ]
      }
    }

    Method [  public method fetch ] {

      - Parameters [1] {
        Parameter #0 [  $index ]
      }
    }
  }
}

Upvotes: 1

Views: 508

Answers (1)

Philipp Palmtag
Philipp Palmtag

Reputation: 1328

After testing your code, I got the return value of 1. Let me quote the PHP manual of count():

Returns the number of elements in array_or_countable. When the parameter is neither an array nor an object with implemented Countable interface, 1 will be returned. There is one exception, if array_or_countable is NULL, 0 will be returned.

As of PHP 7.2, trying to use count() on something uncountable will give a Warning, such as

Parameter must be an array or an object that implements Countable

Demo https://3v4l.org/G0pR3

Upvotes: 2

Related Questions