2009-04-16 4 views
90

저는 누군가 BaseCamp API와의 인터페이스를 위해 작성한 PHP 클래스를 사용하고 있습니다.하이픈으로 연결된 이름으로이 개체 속성에 액세스하려면 어떻게합니까?

내가하고있는 특정 호출은 잘 작동하는 할 일 목록의 항목을 검색하는 것입니다.

내 문제는 반환되는 개체의 속성에 액세스하는 방법을 모르겠습니다. 여기에 반환 된 객체의 위해서 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 부분에 액세스 할 수 있습니다 ?

답변

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

따라서 $ object -> { 'todo-list'}는 하위 개체입니다. 그렇게 설정할 수 있다면, 같은 방식으로 읽을 수도 있습니다.

좀 더 쉽게 할 수있는 배열로 변환하려는 경우 (즉, 명백한 $ 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; 
} 
+0

우리가가는 구문은 내가 찾고있는 문법입니다. 감사! – Ian

+23

그게 짧고 (그리고 내가 뭘 권하는), 변수를 통해 이것을 할 수도 있습니다 :'$ todolist = 'todo-list'; $ x -> $ todolist' – Christian

+0

* 매우 늦은 응답 *, PHP> 5.5, 더 나은 해결책이 있습니다. 객체를 배열에'cast '하거나'get_object_vars()'를 시도하십시오. –

23

가장 간단한 방법을 시도해보십시오.

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

좋은 답변은 미래의 독자를위한 설명과 함께 코드 샘플을 동반합니다. 이 질문을하는 사람이 당신의 대답을 이해할 수 있지만, 당신이 그것에 어떻게 도착했는지 설명하면 무수한 사람들을 도울 수 있습니다. – Stonz2

+1

오, 이것이 진짜 대답입니다. 나는 '.'을 사용하여 객체 속성 이름에 액세스하려고 영원히 노력했습니다. 그것과 이것에서 바로 그 위로 깨끗하게하게된다! – russellmania

관련 문제