2016-09-06 5 views
1

저는 정말 이상한 문제가 있습니다. 구성 파일에서 구성 변수를 선언하고 동일한 페이지의 함수 내에서 이러한 변수에 액세스하려고합니다. 이 함수는 서비스에 대한 SOAP 호출을 만들어 일부 데이터를 가져옵니다.PHP 함수 내에서 전역 범위가 작동하지 않습니다.

이 구성 파일은 다양한 페이지에 포함되어 있지만이 함수에 액세스하면 전역 점수를 선언해도 변수가 비어 있습니다. 내가에 사용자 이름을 입력하면

require_once('config.php'); 

[..] 

$response = fetch_data('1'); 

: 내가 & 호출과 같은 기능을 포함

config.php를 page.php에

// Set environment 
$environment = 'dev'; 

switch($environment){ 
     case 'dev': 
      $username = 'dev'; 
      $client = new SoapClient('http://dev.domain.com/wsdl?wsdl', array('trace' => 1, 'exceptions' => 0)); 
     break; 
     case 'prod'; 
      $username = 'prod'; 
      $client = new SoapClient('http://prod.domain.com/wsdl?wsdl', array('trace' => 1, 'exceptions' => 0)); 
     break; 
     default: 
      $username = 'prod'; 
      $client = new SoapClient('http://prod.domain.com/wsdl?wsdl', array('trace' => 1, 'exceptions' => 0)); 
} 

function fetch_data($request_id){ 
     global $username; 

     $xml_post_string = ' 
      <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ver="https://domain.com"> 
       <soapenv:Header/> 
       <soapenv:Body> 
        <ver:options> 
          <ver:rid>'.$request_id.'</ver:rid> 
          <ver:uid>'.$username.'</ver:uid> 
        </ver:options> 
       </soapenv:Body> 
      </soapenv:Envelope> 
     '; 

     echo '<pre>'; 
     echo 'Var: '.$username; // = empty 
     echo '</pre>'; 

     // Curl headers 
     $headers = array(
      "Content-type: text/xml;charset=\"utf-8\"", 
      "Accept: text/xml", 
      "Cache-Control: no-cache", 
      "Pragma: no-cache", 
      "SOAPAction: "https://domain.com", 
      "Content-length: ".strlen($xml_post_string), 
    ); 

     // Curl options 
     $ch = curl_init(); 
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
     curl_setopt($ch, CURLOPT_URL, 'https://domain.com/call?wsdl'); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
     curl_setopt($ch, CURLOPT_TIMEOUT, 10); 
     curl_setopt($ch, CURLOPT_POST, true); 
     curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request 
     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 

     // Execute Curl call 
     $response = curl_exec($ch); // = credential error 
} 

: 내 (간체) 코드는 다음과 같습니다 XML 문자열 내가 원하는 응답을 얻을 수 있지만 변수를 사용하면 (예를 들어) 나는 $username 빈 값을 얻을.

하지만 왜?

편집 :

프로세스 & 출력 예 break;exit; 변경 및 추가 ** 편집 2 ** 에서 [...] I 보시

require_once('config.php'); 

global $current_user, $wp_query; 

$user              = wp_get_current_user(); 

$user_meta             = get_user_meta($user->data->ID, 'exID'); 
$user_member_number           = trim($user_meta[0]); 

// Set locale for date notation 
setlocale(LC_ALL, 'nl_NL'); 

$policy_id             = $_GET['polis']; 

$customer_call = array(
     'options' => array(
      'Credentials' => array(
       'UserId'          => $username // Normally more credentials like password are required as well 
      ) 
    ) 
); 
$customer_response           = $client->FetchCustomer($customer_call); 

$member_details            = $customer_response->FetchCustomerResult->Result->PlatformCustomer; 

$product_call = array(
     'options' => array(
      'Credentials' => array(
       'UserId'          => $username // Normally more credentials like password are required as well 
      ) 
    ), 
); 
$product_response           = $client->FetchProduct($product_call); 


if($product_response->FetchProductResult->Succeeded){ 
     // Extract results 
     $product_info           = $product_response->FetchProductResult->Result; 

     // Differentiate product response, depending on the ammount of rows returned 
     if($product_info->SummarizedProductInfo >= 2){ 
      $products           = $product_response->FetchProductResult->Result->Summary; 
     }else{ 
      $products           = $product_response->FetchProductResult->Result; 
     } 

     // Policy numbers for given user (for authentication purpose) 
     $member_active_policies        = array(); 

     // Iterate through policies and write policy number to array 
     foreach($products as $product){ 
      array_push($member_active_policies, $product->PolicyNumber); 
     } 

     // Check if requested polis belongs to user 
     if(in_array($policy_id, $member_active_policies)){ 
      // Iterate through products to find the requested 
      foreach($products as $product){ 
       if($product->PolicyNumber == $policy_id){ 

        // Set member variables, all with prefix $member_ 

        // Set product variables, all with prefix $product_ 

        // Fetch information about other members 
        $all_members       = fetch_data(1)->GetProductInfo; 
+0

전체 코드를 게시하면 [$] 변수를 덮어 쓸 수 있습니다. Btw : 당신이 할 수있는 한 어디서나 전역에 의존하지 않도록 노력하십시오. 대신에 다음과 같이 사용하십시오 : static 변수를 가진 클래스 –

+0

어둠 속에서 찌르기 : 당신이'require_once ('config.php')'*가 global *이 아닌 장소. 함수 내에서 파일을 필요로합니다. 전역 변수를 전혀 사용하지 않거나 최소한 전역 변수를 상수로 사용하십시오. – deceze

+0

요구 사항과 함수 호출 간에는 무언가가 일어나야합니다. 어디 [...]를 넣어. 왜냐하면 내가 코드를 실행하면 모든 것이 잘되므로 echo는 dev를 반환한다. –

답변

0

2 문제 간의 코드 이리.

  1. fetch_data 함수가 아무 것도 반환하지 않습니다. 나는 그것이 $xml_post_string을 돌려 보내야한다고 생각하니? 당신이 "자극"를 제공 할 때 사용자 환경은, "DEV"인 경우

  2. 당신이 $xml_post_string을 반환하더라도, 코드 그러므로 스크립트가 fetch_data을 가지고하지 않습니다, 그것은 "exit"에 스크립트를 종료합니다 작동합니다 기능.

+0

죄송합니다.이 게시물에 오타가 있습니다. 그'exit;는'break;'(내 작업 코드에서와 같이) 가정합니다. 또한 내 코드는 변수에 액세스하려고하는 예제입니다. 전체 코드를 추가했습니다. – Maurice

관련 문제