Accessing Object Property with Invalid Name
In PHP, it's possible to encounter objects with properties that have illegal or invalid characters, such as dashes (-). While regular property accessors fail, there are workarounds to retrieve these values.
Solution 1: Bracket Notation
To access a property with an invalid name, use bracket notation with the property name enclosed in curly braces ({}):
$object->{'todo-items'};
Solution 2: Variable Name and Concatenation
Alternatively, assign the property name to a variable and concatenate it with the $object variable:
$todolist = 'todo-items'; echo $object->$todolist;
Example:
Using the example object dump provided:
$x = (object) [ 'completed-count' => '0', 'description' => 'Description String', 'id' => '12345', 'todo-items' => (object) [ 'todo-item' => (object) [ 'completed' => 'false', 'content' => 'content string here', 'created-on' => '2009-04-16T20:33:31Z', 'creator-id' => '23423', 'id' => '234', 'position' => '1', 'responsible-party-id' => '2844499', 'responsible-party-type' => 'Person', 'todo-list-id' => '234234', ], ], ]; echo $x->{'todo-items'}[0]->{'todo-item'}->content;
Additional Tip:
To convert an object to an array, you can use the code snippet provided in the question and answer:
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; }
The above is the detailed content of How Can I Access Object Properties with Invalid Characters in PHP?. For more information, please follow other related articles on the PHP Chinese website!