Classmaps

在 PHP 中创建 SOAP 客户端时,还可以在配置数组中设置 classmap 密钥。这个 classmap 定义了 WSDL 中定义的哪些类型应该映射到实际的类,而不是默认的 StdClass。你希望这样做的原因是因为你可以在这些类上自动完成字段和方法调用,而不必猜测在常规 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 simple returns class as string
        "Book" => MyBook::class,
    ]
]);

配置类映射后,每当执行返回类型 AddressBook 的特定操作时,SoapClient 将实例化该类,用数据填充字段并从操作调用返回它。

// Lets assume 'getAddress(1234)' returns an Address by ID in the database
$address = $soap_client->getAddress(1234);

// $address is now of type MyAddress due to the classmap
echo $address->country;

// Lets assume the same for 'getBook(1234)'
$book = $soap_client->getBook(124);

// We can not use other functions defined on the MyBook class
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 Author type, $author is regular StdClass.
// We can still access fields, but no auto-completion and no custom functions
// to define for the objects.
echo $author->name;