Php 如何使用非法名称访问此对象属性?

Php 如何使用非法名称访问此对象属性?,php,object,Php,Object,我使用的是一个PHP类,是有人编写的,用于与BaseCamp API接口的 我正在做的特殊调用是检索todo列表中的项目,这很好 我的问题是,我不确定如何仅访问返回的对象的todo items属性。以下是返回对象的var_转储: object(stdClass)[6] public 'completed-count' => string '0' (length=1) public 'description' => string 'Description String' (le

我使用的是一个PHP类,是有人编写的,用于与BaseCamp API接口的

我正在做的特殊调用是检索todo列表中的项目,这很好

我的问题是,我不确定如何仅访问返回的对象的
todo items
属性。以下是返回对象的var_转储:

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)
如何访问此对象的
待办事项部分

<?php
$x = new StdClass();
$x->{'todo-list'} = 'fred';
var_dump($x);
另一种可能性:

$todolist = 'todo-list';
echo $x->$todolist;
如果您想将其转换为一个数组,这可能会更容易一些(即明显的
$ret['todo-list']
访问),此代码几乎是从Zend_Config一字不差地获取的,并将为您进行转换

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;
}
试试这个最简单的方法

$obj = $myobject->{'mydash-value'};
$objToArray = array($obj);

虽然这很简短(我也推荐),但您也可以通过变量来实现这一点:
$todolist='todo-list'$x->$todolist
响应非常晚,使用PHP>5.5,有更好的解决方案。要么
将对象强制转换为数组,要么尝试
获取对象变量()!但是试试$x->{$todolist}@JamesBailey,对吧。出于某种原因,当时我认为这只适用于较新版本的PHP,但很显然,这已经存在了一段时间:好的答案伴随着代码示例,并为未来的读者提供了解释。虽然问这个问题的人可能理解你的答案,但解释你是如何得出这个答案的可以帮助无数其他人。哦,这才是真正的答案。我一直试图访问一个包含“.”的对象属性名,这就彻底解决了这个问题!
$obj = $myobject->{'mydash-value'};
$objToArray = array($obj);