Home >Backend Development >PHP Tutorial >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!