如何在不使用 foreach 的情况下修复 "Call to a member function xy on array"?

How to fix "Call to a member function xy on array" without using foreach?

我在数组中存储了一个对象 $image

array(1) { [250]=> object(Magento\Framework\DataObject)#11025 (1) { ["_data":protected]=> array(26) { ["value_id"]=> string(3) "250" ["file"]=> string(58) "/i/n/insetktenschutz-doppeltuer-im-zargenrahmen_37_1_3.jpg"  ... } } }

如果我尝试 return 一个值,例如像这样的文件:

echo $image->getFile();

然后我当然得到 致命错误:未捕获错误:调用数组上的成员函数 getFile()

所以我试着这样称呼它:

$image = $image[0];
echo $image->getFile();

但我得到 Exception #0(Exception):注意:未定义的偏移量:0

所以我尝试将其转换为一个对象:

$image = (object) $image;
echo $image->getFile();

现在我得到 致命错误:未捕获错误:调用未定义的方法 stdClass::getFile()

然后我用了一个foreach:

foreach($image as $i) {
    echo $image->getFile();  // alternative: $image->getData('file')
}

而且有效!为什么它与 foreach 一起工作,没有它我该如何工作?

您可以尝试使用 PHP 的 reset 数组函数来获取数组

的第一个元素
$imageData = reset($image);
echo $imageData->getData("file");

我不认为 php 中有类似函数式 forEach 的东西,无论如何你可以创建一个 ArrayObject 子类来封装迭代逻辑

class MyArray extends ArrayObject {
    public function getData($data){
        foreach($this as $element) {
            $element->getData($data);
        }
    }
}

// and use it
$my = new MyArray(array( /* put your objects here */ ));
$my->getData("file");

编辑

更通用的版本

class MyArray extends ArrayObject {
    public function __call($name, $data){
        foreach($this as $element) {
            $element->$name(...$data);
        }
    }
}
$my = new MyArray(array( /* put your objects here */ ));
$my->getData("file");