【问题标题】:php access object within objectphp访问对象内的对象
【发布时间】:2011-11-02 11:36:30
【问题描述】:

我在 PHP 中有一个对象,我正在使用一个

foreach ($items as $item)

遍历项目。但是,$item 包含另一个名为 $item 的对象,其中包含我需要访问其值的 $type 变量。如何访问 $type 的值?我想做的是:

foreach($items as item){
     if($item->item->type == 'this'){
             //do this
     } elseif ($item->item->type == 'that'){
             //do that
     }
}

但是 $item->item->type 并没有获得那个值。如何访问它并将其用于我的功能?

【问题讨论】:

  • 我不知道它是否与您的示例以外的任何内容相关,但在您的示例代码中,foreach 语句中的“item”缺少应该在其前面的 $。

标签: php oop variables object foreach


【解决方案1】:

你累了吗:

foreach($items as item){
     if($item->type == 'this'){
             //do this
     } elseif ($item->type == 'that'){
             //do that
     }
}

或者您可以调试您的代码以了解发生了什么:

foreach($items as item){
     print_r($item);
}

然后你就可以看到这个$item有什么样的孩子了。

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多