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:
$obj = new stdClass;
$obj->aProperty = 'value';
Additional Syntax Convenience
Alternatively, casting an array to an object provides a more streamlined syntax:
$obj = (object)array('aProperty' => 'value');
print_r($obj);
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3