为什么我不能在foreach PHP中访问object属性

时间:2014-01-26 20:06:58

标签: php arrays object

我正在遍历一些看起来像这样的数据:

Array
(
[0] => stdClass Object
    (
        [id] => 1
        [email] => email@email.com
        [fname] => joe1
        [lname] => someone
        [sent] => 0
    )

[1] => stdClass Object
    (
        [id] => 2
        [email] => email1@email.com
        [fname] => joe2
        [lname] => someone
        [sent] => 0
    )

)

我只是像这样循环遍历数组......

foreach ($recipients as $key => $u) {
    //build email
    echo $u->fname;

            }

没有任何回应,我收到此错误

严重性:注意 消息:尝试获取非对象的属性

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我想问题是$u并不总是您期望的stdClass。我会以这种方式更改代码,看看会发生什么:

foreach ($recipients as $key => $u) {

    if (!is_object($u)) {
         echo "\$u is not an object!";
         var_dump($u);
         exit;
    }

    if (!property_exists($u, 'fname')) {
         echo "property fname is not defined!";
         var_dump($u);
    }

    echo $u->fname;
}