Home  >  Article  >  Backend Development  >  How to Create Object Literals in PHP

How to Create Object Literals in PHP

Susan Sarandon
Susan SarandonOriginal
2024-10-20 07:02:02934browse

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" ]
};

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';

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

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

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!

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