不能将stdClass类型的对象用作数组


Cannot use object of type stdClass as array

首先,我不是Php极客。。所以请原谅我对PHP的了解不多。我使用的是前端带有Flex的AMFPHP2。我可以从后端以类型化对象的形式提取数据,但当我尝试保存时,我遇到了如下问题:

<br /><b>Fatal error</b>:  Cannot use object of type stdClass as array in <b>/mnt/array1/share/htdocs/htdocs/admin/application/amf/services/Item.php</b> on line <b>88</b><br />

以下是引发此错误的代码:

Line86    public function saveCollection($collection) {
Line87        for ($i=0; $i<count($collection); $i++) {
Line88            $this->saveItem($collection[$i]);
Line89        }
Line90    }

以下是我的VO类:项目VO.php

class ItemVO {
..
..
var $_explicitType = "ItemVO";
..
..
}

项目VO.as

package models.vo {
    [RemoteClass(alias="ItemVO")]  
    public class ItemVO {
...
...
    }
}

这是我的文件夹结构:

-root/
------*.html
------*.swf
------application/
-----------------amf/
--------------------/index.php
--------------------/models/vo/all vo files
--------------------/services/all services
-----------------libraries/
--------------------------/Amfphp/

这是我的index.php

<?php
require_once dirname(dirname(__FILE__)) . '/libraries/Amfphp/ClassLoader.php';
$config = new Amfphp_Core_Config();
$config->serviceFolderPaths = array(dirname(__FILE__) . '/services/');
$voFolders = array(dirname(__FILE__) . '/models/vo/');
$customClassConverterConfig = array(‘customClassFolderPaths’ => $voFolders);
$config->pluginsConfig['AmfphpCustomClassConverter'] = $customClassConverterConfig;
$gateway = Amfphp_Core_HttpRequestGatewayFactory::createGateway($config);
$gateway->service();
$gateway->output();
?>

任何帮助都将不胜感激。谢谢

错误消息是自我解释的。您可以使用例如:

public function saveCollection($collection) {
 foreach ($collection as $value) {
          $this->saveItem($value);
       }
   }

我对该错误的基本理解是,您试图将访问对象视为数组。

这通常意味着您正在执行$something['something']而不是正确的$something->something

saveCollection中的$collection参数是数组还是对象?

尝试将88号线替换为:

 $this->saveItem($collection->$i);

编辑-

正如我刚刚在评论中意识到的那样,它无论如何都不应该起作用,因为你正在尝试计算stdClass。正如其他人在回答中提到的那样,使用for each应该可以达到目的。

您引用的是stdClass对象,就像数组一样,两者不是一回事。出于您的目的,您可以将其投射为数组:

public function saveCollection($collection) {
    $collection = (array)$collection;
    for ($i=0; $i<count($collection); $i++) {
        $this->saveItem($collection[$i]);
    }
}

注意:将对象强制转换为数组并不总是有效的,但由于看起来您希望传递一个类似数组的结构,所以它可能会很好地工作。