如何使用连字符名称访问此对象属性?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (28)

我使用的是一个PHP类,有人写它是为了与Basecamp API接口。

我正在做的特别调用是检索todo列表中的项,这很好。我不知道如何访问todo-items属性的属性。这是变量_返回对象的转储:

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

提问于
用户回答回答于
<?php
$x = new StdClass();
$x->{'todo-list'} = 'fred';
var_dump($x);

所以,$Object->{‘todo-list’}是子对象.。如果你可以这样设置它,那么你也可以用同样的方式阅读它。

如果你想把它转换成一个数组,这段代码几乎是从Zend逐字获取的。

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);

扫码关注云+社区