当变量似乎是数组而不是对象时,出现奇怪的stdClass as数组错误


Strange stdClass as array error when the variable seems to be an array, not an object

我注意到了一些修补问题的东西:如果我返回$this->_data而不是$this->_data[0]-,然后使用$object->data()[0],它确实按预期工作。。。但是,我希望返回函数中的[0]。

在你开始说这是一个重复之前,这个问题与大多数其他关于这个错误的问题不同。

我在尝试访问我班上的$this->_data[0]时遇到以下错误:

Cannot use object of type stdClass as array

这是触发错误的功能/行:

  public function data(){
      return $this->_data[0]; //<- line 75
  }

据我所知,当我试图像使用数组一样使用对象时,就会出现这种错误。然而,当我var_dump($this->_data)时,我得到以下结果:

array(1) {
    [0]=> object(stdClass)#34 (10) { 
        ["uid"]=> string(1) "0"
        ["nid"]=> string(3) "374"
        ["id"]=> string(8) "YicnaxYw"
        ["txt_content"]=> NULL
        ["path"]=> string(32) "/uploads/images/png/YicnaxYw.png"
        ["image"]=> string(1) "1"
        ["timestamp"]=> string(10) "1448192959"
        ["file_ext"]=> string(3) "png"
        ["file_type"]=> string(9) "image/png"
        ["originalFilename"]=> string(23) "2015-11-22_12-49-17.png"
    }
}

其中,该变量显然是具有[0]元素的array(1)类型。。

有人能告诉我我做错了什么吗?

提前谢谢。

@Xeli $this->_data[0]->nid导致相同错误


致命错误:无法将stdClass类型的对象用作/home3/ramzes/includes/classes/UploadItem.php中75
行的数组

UploadItem.php:75

  public function data(){
      return $this->_data[0]->nid;
  }

$this->_data[0]是一个fetchAll(PDO::FETCH_OBJ)对象,其结果来自查询

编辑:

我已经在设置了一个测试http://ideone.com/66I3wO-我将您的对象存储在一个数组中,我可以访问$this->_data[0]->nid。

<?php
class Test
{
    public $_data = [];
    public function __construct() {
        $this->_data[0] = (object) [
            'uid' => '0',
            'nid' => '374',
            'id' => 'YicnaxYw',
            'txt_content' => null,
            'path' => '/uploads/images/png/YicnaxYw.png',
            'image' => '1',
            'timestamp' => '1448192959',
            'file_ext' => 'png',
            'file_type' => 'image/png',
            'originalFilename' => '2015-11-22_12-49-17.png'
        ];
    }
    public function data(){
        return $this->_data[0];
    }
}
$test = new Test();
echo $test->_data[0]->nid;
var_dump( $test->data() );

我认为PDO返回一个对象,该对象是通过以下方式实现的:http://php.net/manual/en/class.iteratoraggregate.php

当您对它进行var_dump时,它看起来像一个数组,但事实并非如此。

您可以将数据功能更改为:

function data() {
    foreach($this->_data as $data) {
        return $data;
    }
}

如果显式转换为数组,则可以访问所需的索引:

$return = (array) $this->_data;
return $return[0];