Recipe 14.11. Mapping XML Schema Data Types to PHP Classes


14.11.1. Problem

You want to automatically convert a SOAP object to a PHP object.

14.11.2. Solution

Define a PHP class and tell the SOAPClient to map a SOAP object to it using the classmap option:

class PHPStockType {}; // stub class $opts = array('classmap' => array('StockType' => 'PHPStockType')); $client = new SOAPClient($wsdl_url, $opts);

Now any StockType structure will be converted to a PHPStockType.

14.11.3. Discussion

Class mapping can be very helpful in making SOAP objects easier to use. In particular, look to see where you can define a __toString( ) method to control how an object displays. It can also be useful to implement the IteratorAggregate and the ArrayAccess interfaces.

For example, a stock quote object may return a large amount of data about a stock: the current price, the 52-week high and low prices, the ticket symbol, etc. However, the key piece of data is the current price, so you may want to implement code such as this:

<?php class PHPStockType {     public function __toString() {         return (string) $this->currentPrice;     } } ?>

All the other data is still available, but when you print out the object, you get the most important value.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net