SOAP WebService PHP 客户端参数初始化


soap webservice php client parameters initialization

当我使用初始化变量作为参数调用远程方法时,我遇到了问题,然后我在 resutl 中什么也得不到,但是当我将值作为参数传递时,一切正常! 这是PHP中的代码:

$serviceWsdl = 'http://localhost:8080/Test/services/Test?wsdl';
$client = new SoapClient($serviceWsdl);
function getFirstName($code){
    $firstname = $client->getFirstName(array('code' => $code));
    return $firstname->return;
}
$c=1;
$result=getFirstName($c);
var_dump($result);

你应该阅读一些关于PHP中作用域的信息。函数中未设置变量client,因为这是另一个作用域。有一些解决方案可以解决这个问题。你可以用global得到变量,但这并不酷。

function getFirstName($code){
    global $client;
    $firstname = $client->getFirstName(array('code' => $code));
    return $firstname->return;
}

你不应该那样做。当你使用全局变量时,你不知道你的变量来自哪里。

另一种解决方案是将变量定义为函数参数。

function getFirstName($code, $client) {

那就好多了。如果您使用类,则可以将变量定义为更好的类变量。例如:

class ApiConnection {
    private $serviceWsdl = 'http://localhost:8080/Test/services/Test?wsdl';
    private $client;
    public function __construct() {
        $this->client = new SoapClient($this->serviceWsdl);
    }
    public function getFirstName($code){
        $firstname = $this->client->getFirstName(array('code' => $code));
        return $firstname->return;
    }
}

我还没有测试过该代码,但使用类要好得多。