I have a function which returns object array like that:
<?php
function sth()
{
return (object) array(
"obj1" => $obj1,
"obj2" => $obj2,
"obj3" => $obj3
);
}
$obj = sth();
echo $obj;
?>
Here I want to define $obj’s default value.It will return default value instead of $obj1,$obj2,$obj3.
How can I define a default value?
You need to add actual functionality to the object to achieve this. Simply casting an array to an object only creates an object that holds some values, it is not very different from an array. There’s no notion of “default values” for either arrays or objects, the only way to simulate this concept is by implementing it using magic methods, in this case
__toString. As such, you need to create a class akin to this: