6
votes

I'm implementing an Iterator interface and if I implement it returning scalar (following the reference http://php.net/manual/en/class.iterator.php), I got this error:

TypeError: Return value of Collection::key() must be an instance of scalar, integer returned

The class implementation:

class Collection implements \Iterator
{
    public function key(): \scalar
    {
        return key($this->colecao);
    }
    // other methods implementations...
}

According to the PHP reference, integer should be considered a scalar value (http://php.net/manual/en/migration70.new-features.php):

Scalar type declarations come in two flavours: coercive (default) and strict. The following types for parameters can now be enforced (either coercively or strictly): strings (string), integers (int), floating-point numbers (float), and booleans (bool).

Is there some mistake in my code your would it be a bug?

Thank you for any explanation!

1
public function key(): int is what you need. You have to specify which scalar type it returns.Don't Panic
Return types can only be php.net/manual/en/… No such thing as scalar that I have heard ofRiggsFolly
The types shown in PHP documentation are not real types that you can use in code, they're just meant to be descriptive to human readers. E.g. there's no type named mixed, it just means that the function can return multiple types.Barmar
@Don'tPanic, thank for the help. I had put the return type with int, but I had no success.alexandrecintra

1 Answers

5
votes

PHP does not have a type known as \scalar. PHP only supports those types. And your \scalar type looks like it is another class.