How to Create Object Literals in PHP

Susan Sarandon
Release: 2024-10-20 07:02:02
Original
933 people have browsed it

How to Create Object Literals in PHP

Creating Object Literals in PHP

In JavaScript, creating anonymous objects is achieved using the curly brace syntax, as seen below:

var object = { 
    p : "value", 
    p1 : [ "john", "johnny" ]
};
Copy after login

However, in PHP, the concept of "anonymous objects" does not apply. All PHP objects belong to a specific class, with the default class being stdClass. To create an object of type stdClass, use the syntax:

$obj = new stdClass;
$obj->aProperty = 'value';
Copy after login

Additionally, you can utilize a convenient method to convert an array into an object, resulting in more succinct syntax:

$obj = (object)array('aProperty' => 'value');
Copy after login

It's important to note that type casting an array to an object may lead to unexpected outcomes for array keys that are not valid PHP variable names. For instance, keys beginning with digits may produce unpredictable results.

The above is the detailed content of How to Create Object Literals 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!