As per the PHP Manual:
If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. If the value was NULL, the new instance will be empty. An array converts to an object with properties named by keys and corresponding values. Note that in this case before PHP 7.2.0 numeric keys have been inaccessible unless iterated.
When you cast a string to an object the value of that string will be saved as an attribute. The default name is given which is scalar
. Even an empty string is still considered to hold a value.
In PHP you have multiple ways of creating an empty object.
An example taken from https://www.php.net/manual/en/language.types.object.php#118679
<?php
$obj1 = new \stdClass; // Instantiate stdClass object
$obj2 = new class{}; // Instantiate anonymous class
$obj3 = (object)[]; // Cast empty array to object
var_dump($obj1); // object(stdClass)#1 (0) {}
var_dump($obj2); // object(class@anonymous)#2 (0) {}
var_dump($obj3); // object(stdClass)#3 (0) {}
Another way would be to cast a null value to an object as N69S shown:
$object = (object)null; // Same as (object)[]
And of course you can convert an associative array to an object:
$object = (object)['a' => 123];
// object(stdClass)#1 (1) {
// ["a"]=>
// int(123)
// }