简体   繁体   English

如何在PHP类方法中接收特定接口的数组?

[英]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.

相关问题 为什么PHP的in_array()方法在数组中识别出对象的特定实例的存在? - How come PHP's in_array() method recognizes the existence of a specific instance of an object, in an array? 抽象方法中的PHP类型提示接口和方法实现中的类型提示接口的子类 - PHP type hint interface in abstract methods and type hint interface's child class in method implementation 无法通过 PHP 中的表单 POST 方法接收数组 - Cant receive an array by form POST method in PHP 无法在 PHP post 方法中接收数组 - Unable to receive array in PHP post method 如何在PHP的类方法中返回数组长度? - How to return array length in class method in php? 如何将define()方法与在PHP中定义为特定类的“类常量”一起使用? - How to use defined() method with 'Class Constants' that are defined into a specific class in PHP? PHP类:如何将make方法的数据转换为类属性? - PHP class: how to a make method's data to become the class properties? php一个特定类的数组或列表 - php an array or list of a specific class OOP PHP - 如何有选择地调用类的构造函数中定义的特定方法? - OOP PHP — How to selectively call a specific method defined in a class' constructor? PHP类:ArrayAccess接口-是否可以在类中直接使用数组接口? - PHP classes: ArrayAccess interface - Is it possible to use the array interface directly in a class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM