How to Access Class Properties with Spaces in PHP?

Susan Sarandon
Release: 2024-10-18 15:40:03
Original
964 people have browsed it

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

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!