类扩展SOAP中的PHP变量范围问题


PHP variable scope issue in class extending SOAP

我正在研究一种验证帐号的方法。$account_number是从另一个函数传入进行验证的。在从函数传递到类的过程中,我遇到了变量的作用域问题。我有它的工作,但我诉诸于使用$GLOBALS来绕过范围界定问题。我觉得一定有更好的办法。这是我所拥有的:

$acct;
$subAcct;
$chart;
$object;
$subObject;
$project;
function verifyACCT($account_number){
    //Strip all but numbers and letters, truncate to first seven digits, and convert to uppercase
    $account_number = strtoupper(preg_replace("/[^a-z0-9]/i", "", $account_number));
    $GLOBALS['$acct'] = substr($account_number, 0, 7);
    $GLOBALS['$subAcct'] = substr($account_number, 8);
    $GLOBALS['$chart'] = "XX";
    $GLOBALS['$object'] = "0000";
    $GLOBALS['$subObject'] = null;
    $GLOBALS['$project'] = null;
    class ACCTSoapClient extends SoapClient {
        public function __doRequest($request, $location, $action, $version, $one_way=0) {
            $request = '<?xml version="1.0" encoding="utf-8"?>
            <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <soap:Body>
            <isValidAccountString xmlns="http://URL/">
            <chartOfAccountsCode xmlns="">'.$GLOBALS['$chart'].'</chartOfAccountsCode>
            <accountNumber xmlns="">'.$GLOBALS['$acct'].'</accountNumber>
            <subAccountNumber xmlns="">'.$GLOBALS['$subAcct'].'</subAccountNumber>
            <objectCode xmlns="">'.$GLOBALS['$object'].'</objectCode>
            <subObjectCode xmlns="">'.$GLOBALS['$subObject'].'</subObjectCode>
            <projectCode xmlns="">'.$GLOBALS['$project'].'</projectCode>
            </isValidAccountString>
            </soap:Body>
            </soap:Envelope>';
            return parent::__doRequest($request, $location, $action, $version, $one_way);
        }
    }
    $client = new ACCTSoapClient("https://URL?wsdl", array("connection_timeout"=>5, 'exceptions' => 0));
    try {
        $result = $client->isValidAccountString(null);
        return ($result->return); //boolean (1 for valid, null for invalid)
    } catch(SoapFault $e) {
        echo 1;
    } catch(Exception $e) {
        echo 1;
    }
}

为了避免使用$_GLOBALS(这被认为是非常糟糕的做法),您需要重构代码

您目前正在将过程代码方法与面向对象编程相结合。

  1. 分离类ACCTSoapClient并创建一个新的类用于验证
  2. 使用依赖项注入在验证类中设置SoapClient类。或者为了简单起见,只需在构造函数中实例化它
  3. 将当前全局变量放入带有访问修饰符protectedprivate的新验证类中
  4. 在验证类中创建一个public function verify
  5. 现在实例化验证类并调用verify方法
  6. verify方法将调用SOAP类的doRequest方法并返回响应

我希望这能帮助你走上正轨。