[英]How to receive specific interface's array in PHP class method?
I want to receive array of MyInterface as the in the below code. 我想接收下面代码中的MyInterface数组。
public function saveMultiple(
\Path\To\MyInterface $attachLinks[]
);
The above code doesn't work. 上面的代码不起作用。
So please don't tell me that just remove \\Path\\To\\MyInterface
and to use a variable $attachLinks
. 所以请不要告诉我只需删除
\\Path\\To\\MyInterface
并使用变量$attachLinks
。 I'm already aware of that but this is something which I require. 我已经意识到这一点,但这是我需要的。
There are no generic types in php, so you can not specify type «array of something». php中没有泛型类型,所以你不能指定类型«数组的东西»。
But you may do a trick. 但你可能会做一个技巧。 Check types of elements in array.
检查数组中的元素类型。
array_walk($attachLinks, function (\Path\To\MyInterface $item) {});
If you wrap it in assert, you will be able to disable this check. 如果将其包装在断言中,则可以禁用此检查。
assert('array_walk($attachLinks, function (\Path\To\MyInterface $item) {})');
So far this is what can be done using PHP7
. 到目前为止,这是使用
PHP7
可以完成的PHP7
。 Till date passing arrays with specific type is not possible. 直到日期传递具有特定类型的数组是不可能的。
public function saveMultiple(
array $attachLinks
);
It'll now at least make sure that the method only gets array as parameter. 现在至少要确保该方法只将数组作为参数。
Maybe you can use some type of setter like: 也许你可以使用某种类型的setter:
private $attachLinks = [];
public function setter(MyInterface $var)
{
$this->attachLinks[] = $var;
}
And than use a $this->attachLinks in your function 而不是在你的函数中使用$ this-> attachLinks
public function saveMultiple() {
print_r($this->attachLinks);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.