Convert StdClass objects to SOAP compliant objects

Description:

Having an obtained StdClass Object, we require to change it into a SOAP structure object or Array compliant.

Solution:

Converting a StdClass Object with PhP basically means iterating the object and populating the public properties with elements from the provided object/array.

First we get the public properties using the PhP Reflection Class:

$reflect = new ReflectionClass($this);
$properties = $reflect->getProperties (ReflectionProperty::IS_PUBLIC);

Having these properties, we simply iterate them as follows:

foreach($properties as $property) {
$propertyName = $property->getName();
if (isset($data[$propertyName])) {
$this->{$propertyName} =  (is_object($data[$propertyName])) ?  (array)$data[$propertyName] : $data[$propertyName];
}
}

Additionally, we can start by converting the $data object into Array:

if (is_object($data)) {
$data = (array)$data;
}

Advertisements

About admin

Just another php developer trying to give something back to the community.
This entry was posted in Best practices, PhP and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s