property_name. However, when the property name contains spaces, the dot opera"/> property_name. However, when the property name contains spaces, the dot opera">

Home  >  Article  >  Backend Development  >  How to Access Class Properties with Spaces in PHP?

How to Access Class Properties with Spaces in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-10-18 15:40:03965browse

How to Access Class Properties with Spaces in PHP?

Accessing Class Properties with Spaces

In object-oriented programming, properties can be accessed using the dot operator ("."), which is a shortcut for $object->property_name. However, when the property name contains spaces, the dot operator cannot be used.

Problem:

Consider the following stdClass object:

stdClass Object (
    [Sector] => Manufacturing
    [Date Found] => 2010-05-03 08:15:19
)

How can we access the "[Date Found]" property of this object using standard PHP syntax?

Solution:

To access properties with spaces, we can use curly braces ({}) and single quotes ('') or double quotes (""). Here's an example:

<code class="php">$object = new stdClass();
$object->{'Date Found'} = '2010-05-03 08:15:19';

echo $object->{'Date Found'}; // Output: 2010-05-03 08:15:19</code>

The curly braces act as a placeholder for the property name, allowing us to access it dynamically. We can also use the following syntax:

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

Here, the double quotes are not necessary because the curly braces and the single quotes serve the same purpose.

The above is the detailed content of How to Access Class Properties with Spaces in PHP?. 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