잘못된 이름으로이 객체 속성에 어떻게 액세스합니까?


115

BaseCamp API와 인터페이스하기 위해 누군가 작성한 PHP 클래스를 사용하고 있습니다.

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

내 문제 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이 개체 의 부분에 어떻게 액세스 할 수 있습니까?

답변:


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
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.