Home >Backend Development >PHP Tutorial >How to Access PHP Object Properties with Spaces in their Names?

How to Access PHP Object Properties with Spaces in their Names?

Susan Sarandon
Susan SarandonOriginal
2024-10-18 15:41:02287browse

How to Access PHP Object Properties with Spaces in their Names?

Retrieving Class Properties with Spaces in Property Names

When working with PHP objects, you may encounter properties with spaces in their names. This can present a challenge when accessing these properties using the traditional dot syntax.

Consider the following stdClass object:

<code class="php">$object = (object) [
    'Sector' => 'Manufacturing',
    'Date Found' => '2010-05-03 08:15:19'
];</code>

While you can access the 'Sector' property using $object->Sector, you cannot do the same for 'Date Found' using $object->Date Found. To resolve this, you can use the following syntax:

<code class="php">$dateFound = $object->{'Date Found'};</code>

By enclosing the property name in curly braces, you can effectively escape any spaces or other special characters. This allows you to access the property as though it were one word.

Therefore, to answer your specific question:

How to access the [Date Found] property:

Use the following syntax:

<code class="php">$dateFound = $object->{'Date Found'};</code>

This will successfully retrieve the value of the 'Date Found' property.

The above is the detailed content of How to Access PHP Object Properties with Spaces in their Names?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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