I'm using a third party storage system that only returns me stdClass objects no matter what I feed in for some obscure reason. So I'm curious to know if there is a way to cast/convert an stdClass object into a full fledged object of a given type.
For instance something along the lines of:
//$stdClass is an stdClass instance
$converted = (BusinessClass) $stdClass;
I am just casting the stdClass into an array and feed it to the BusinessClass constructor, but maybe there is a way to restore the initial class that I am not aware of.
Note: I am not interested in 'Change your storage system' type of answers since it is not the point of interest. Please consider it more an academic question on the language capacities.
Cheers
See the manual on Type Juggling on possible casts.
The casts allowed are:
You would have to write a Mapper that does the casting from stdClass to another concrete class. Shouldn't be too hard to do.
Or, if you are in a hackish mood, you could adapt the following code:
which pseudocasts an array to an object of a certain class. This works by first serializing the array and then changing the serialized data so that it represents a certain class. The result is unserialized to an instance of this class then. But like I said, it's hackish, so expect side-effects.
For object to object, the code would be
And yet another approach using the decorator pattern and PHPs magic getter & setters:
To move all existing properties of a
stdClass
to a new object of a specified class name:Usage:
Output:
This is limited because of the
new
operator as it is unknown which parameters it would need. For your case probably fitting.I have a very similar problem. Simplified reflection solution worked just fine for me:
Yet another approach.
The following is now possible thanks to the recent PHP 7 version.
In this example, $foo is being initialized as an anonymous class that takes one array or stdClass as only parameter for the constructor.
Eventually, we loop through the each items contained in the passed object and dynamically assign then to an object's property.
To make this approch event more generic, you can write an interface or a Trait that you will implement in any class where you want to be able to cast an stdClass.
You can use above function for casting not similar class objects (PHP >= 5.3)
EXAMPLE: