Coder Perfect

How do I get access to this illegally named object property?

Problem

I’m interacting with the BaseCamp API using a PHP class created by someone.

The call I’m making is to retrieve items from a todo list, and it’s working properly.

My problem is, I’m not sure how to access just the todo-items property of the object that is returned. Here’s the var_dump of the returned object:

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)

What is the best way to go to the todo-items section of this object?

Asked by Ian

Solution #1

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

So, $object->{‘todo-list’} is the sub-object. If you can set it up that way, you can read it that way as well:

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

Another possibility:

$todolist = 'todo-list';
echo $x->$todolist;

If you want to convert it to an array, which is a little easier to work with (for example, accessing $ret[‘todo-list’]), this code is virtually verbatim from Zend Config and will convert it for you.

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

Answered by Alister Bulman

Solution #2

Try this easy method!

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

Answered by Nikunj Dhimar

Post is based on https://stackoverflow.com/questions/758449/how-do-i-access-this-object-property-with-an-illegal-name