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


115

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

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

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

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此对象的一部分?

Answers:


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

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

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

另一种可能性:

$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;
}

24
尽管这很简短(而且我很推荐),但是您也可以通过变量来做到这一点:$todolist='todo-list'; $x->$todolist
Christian

响应非常晚,对于PHP> 5.5,有更好的解决方案。cast将该对象放入数组,或尝试get_object_vars()
Owen Beresford

1
@christian很好!但是请尝试$ x-> {$ todolist}
James Bailey,

@JamesBailey,对。出于某种原因,当时我以为只有更新版本的PHP才提供此功能,但显然已经存在了一段时间:3v4l.org/nf15N
Christian

28

试试最简单的方法!

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

4
代码示例附带了良好的答案,并为以后的读者提供了解释。提出这个问题的人可能会理解您的答案,但解释一下您的提出方式会对其他人有所帮助。
Stonz2 2014年

2
哦,这是真正的答案。我一直试图用'。'访问对象属性名称。在里面,这清理了吧!
russellmania
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.