Home >Backend Development >PHP Tutorial >Can Anonymous Objects Be Created in PHP Like in JavaScript?
Creating Anonymous Objects in PHP
In JavaScript, anonymous objects can be created easily. However, can this technique also be applied to PHP?
Terminology Explanation
The term "anonymous" is not entirely accurate when discussing objects. Rather, it should be referred to as "object of anonymous type."
PHP Object Creation
In PHP, all objects have a designated class. The default class is stdClass, and objects of this class can be instantiated using the following syntax:
<code class="php">$obj = new stdClass; $obj->aProperty = 'value';</code>
Additional Syntax Convenience
Alternatively, casting an array to an object provides a more streamlined syntax:
<code class="php">$obj = (object)array('aProperty' => 'value'); print_r($obj);</code>
Array Casting Caveat
It's worth noting that casting an array to an object may produce unexpected results. Array keys that are not valid PHP variable names, such as those starting with digits, may behave unexpectedly.
The above is the detailed content of Can Anonymous Objects Be Created in PHP Like in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!