如何使用非法名称访问此对象属性? [英] How do I access this object property with an illegal name?

查看:100
本文介绍了如何使用非法名称访问此对象属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用有人编写的PHP类来与BaseCamp API交互.

I'm using a PHP class someone wrote to interface with the BaseCamp API.

我正在执行的特定呼叫是检索待办事项列表中的项目,效果很好.

The particular call I'm doing is to retrieve the items in a todo list, which works fine.

我的问题是,我不确定如何仅访问返回的对象的todo-items属性.这是返回对象的var_dump:

My problem is, I'm not sure how to access just the todo-items property of the object that is returned. Here's the var_dump of the returned object:

object(stdClass)[6]
  public 'completed-count' => string '0' (length=1)
  public 'description' => string 'Description String' (length=89)
  public 'id' => string '12345' (length=7)
  public 'milestone-id' => string '' (length=0)
  public 'name' => string 'Error Reports' (length=13)
  public 'position' => string '1' (length=1)
  public 'private' => string 'false' (length=5)
  public 'project-id' => string '58904' (length=7)
  public 'tracked' => string 'false' (length=5)
  public 'uncompleted-count' => string '1' (length=1)
  public 'todo-items' => 
    object(stdClass)[3]
      public 'todo-item' => 
        object(stdClass)[5]
          public 'completed' => string 'false' (length=5)
          public 'content' => string 'content string here' (length=133)
          public 'created-on' => string '2009-04-16T20:33:31Z' (length=20)
          public 'creator-id' => string '23423' (length=7)
          public 'id' => string '234' (length=8)
          public 'position' => string '1' (length=1)
          public 'responsible-party-id' => string '2844499' (length=7)
          public 'responsible-party-type' => string 'Person' (length=6)
          public 'todo-list-id' => string '234234' (length=7)
  public 'complete' => string 'false' (length=5)

如何访问此对象的todo-items部分?

How can I access the todo-items portion of this object?

推荐答案

<?php
$x = new StdClass();
$x->{'todo-list'} = 'fred';
var_dump($x);

因此,$object->{'todo-list'}是子对象.如果可以这样设置,那么您也可以按照相同的方式阅读它:

So, $object->{'todo-list'} is the sub-object. If you can set it like that, then you can also read it the same way:

echo $x->{'todo-list'};

另一种可能性:

$todolist = 'todo-list';
echo $x->$todolist;

如果您想将其转换为数组,可以更轻松一些(即显而易见的$ret['todo-list']访问),则该代码几乎完全从Zend_Config中获取,并将为您转换.

If you wanted to convert it to an array, which can be a little more easily (ie the obvious $ret['todo-list'] accessing), this code is taken almost verbatim from Zend_Config and will convert for you.

public function toArray()
{
    $array = array();
    foreach ($this->_data as $key => $value) {
        if ($value instanceof StdClass) {
            $array[$key] = $value->toArray();
        } else {
            $array[$key] = $value;
        }
    }
    return $array;
}

这篇关于如何使用非法名称访问此对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆