복붙노트

하이픈으로 연결된 이름으로이 객체 속성에 액세스하려면 어떻게합니까?

PHP

하이픈으로 연결된 이름으로이 객체 속성에 액세스하려면 어떻게합니까?

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

내가하고있는 특정 호출은 제대로 작동하는 todo 목록의 항목을 검색하는 것입니다.

내 문제는 반환되는 개체의 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)

이 객체의 할 일 항목 부분에 어떻게 액세스 할 수 있습니까?

해결법

  1. ==============================

    1.

    <?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;
    }
    
  2. ==============================

    2.이 간단한 방법을 시도하십시오!

    이 간단한 방법을 시도하십시오!

    $obj = $myobject->{'mydash-value'};
    $objToArray = array($obj);
    
  3. from https://stackoverflow.com/questions/758449/how-do-i-access-this-object-property-with-a-hyphenated-name by cc-by-sa and MIT license