Home > Backend Development > PHP Tutorial > How Can I Access Object Properties with Invalid Characters in PHP?

How Can I Access Object Properties with Invalid Characters in PHP?

DDD
Release: 2024-12-14 01:57:10
Original
528 people have browsed it

How Can I Access Object Properties with Invalid Characters in PHP?

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'};
Copy after login

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;
Copy after login

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;
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template