Classmaps
suggest changeWhen creating a SOAP Client in PHP, you can also set a classmap key in the configuration array. This classmap defines which types defined in the WSDL should be mapped to actual classes, instead of the default StdClass. The reason you would want to do this is because you can get auto-completion of fields and method calls on these classes, instead of having to guess which fields are set on the regular StdClass.
class MyAddress {
public $country;
public $city;
public $full_name;
public $postal_code; // or zip_code
public $house_number;
}
class MyBook {
public $name;
public $author;
// The classmap also allows us to add useful functions to the objects
// that are returned from the SOAP operations.
public function getShortDescription() {
return "{$this->name}, written by {$this->author}";
}
}
$soap_client = new SoapClient($link_to_wsdl, [
// Other parameters
"classmap" => [
"Address" => MyAddress::class, // ::class returns the class name as a string
"Book" => MyBook::class,
]
]);
After configuring the classmap, whenever you perform a certain operation that returns a type Address or Book, the SoapClient will instantiate that class, fill the public properties from the response, and return it. Unmapped types are still stdClass (the correct class name; PHP treats StdClass as the same class).
// Let's assume getAddress(1234) returns an Address for that id
$address = $soap_client->getAddress(1234);
// $address is now of type MyAddress due to the classmap
echo $address->country;
// Let's assume the same for getBook(1234)
$book = $soap_client->getBook(1234);
// Methods defined on MyBook can be called on the result
echo $book->getShortDescription();
// Any type defined in the WSDL that is not defined in the classmap
// will become a regular stdClass object
$author = $soap_client->getAuthor(1234);
// No classmap for the Author type, so $author is a stdClass.
// We can still access fields, but no auto-completion and no custom functions
// to define for the objects.
echo $author->name;
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents