Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

php - Type hinting - specify an array of objects

How can I specify the argument type as an array? Say I have a class named 'Foo':

class Foo {}

and then I have a function that accepts that class type as an argument:

function getFoo(Foo $f) {}

When I pass in an array of 'Foo's I get an error, saying:

Catchable fatal error: Argument 1 passed to getFoo() must be an instance of Foo, array given

Is there a way to overcome this issue? maybe something like

function getFoo(Foo $f[]) {}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to ensure you are working with "Array of Foo" and you want to ensure methods receive "Array of Foo", you can:

class ArrayOfFoo extends ArrayObject {
    public function offsetSet($key, $val) {
        if ($val instanceof Foo) {
            return parent::offsetSet($key, $val);
        }
        throw new InvalidArgumentException('Value must be a Foo');
    }
}

then:

function workWithFoo(ArrayOfFoo $foos) {
    foreach ($foos as $foo) {
        // etc.
    }
}

$foos = new ArrayOfFoos();
$foos[] = new Foo();
workWithFoo($foos);

The secret sauce is that you're defining a new "type" of "array of foo", then passing that "type" around using type hinting protection.


The Haldayne library handles the boilerplate for membership requirement checks if you don't want to roll your own:

class ArrayOfFoo extends HaldayneBoostMapOfObjects {
    protected function allowed($value) { return $value instanceof Foo; }
}

(Full-disclosure, I'm the author of Haldayne.)


Historical note: the Array Of RFC proposed this feature back in 2014. The RFC was declined with 4 yay and 16 nay. The concept recently reappeared on the internals list, but the complaints have been much the same as levied against the original RFC: adding this check would significantly affect performance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...