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
Release: 2024-10-18 15:41:02
Original
274 people have browsed it

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

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

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

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!

source:php
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template