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 ]
}
}
}
}
-
why don't you manually count if you can loop in it ??vichu– vichu2017年10月26日 14:27:33 +00:00Commented Oct 26, 2017 at 14:27
-
Out of curiosity, how do you work with external PHP code you don't have the source for?M. Eriksson– M. Eriksson2017年10月26日 14:31:56 +00:00Commented Oct 26, 2017 at 14:31
-
1The correct count doesn't happen to be 1, does it?Don't Panic– Don't Panic2017年10月26日 14:33:24 +00:00Commented Oct 26, 2017 at 14:33
-
If it is 1 we know the answer ;)Philipp Palmtag– Philipp Palmtag2017年10月26日 14:35:01 +00:00Commented Oct 26, 2017 at 14:35
-
@MagnusEriksson with difficulty...cosmorogers– cosmorogers2017年10月26日 14:42:15 +00:00Commented Oct 26, 2017 at 14:42
1 Answer 1
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
2 Comments
count(SpecialArray) is returning the correct count, eg if there are 7 elements in the SpecialArray (that I can loop over in a foreach, etc), count(SpecialArray) returns 7!!!!