php
  • oop
  • xpath
  • simplexml
  • 2017-01-20 32 views 1 likes 
    1
    class ad_xml_model extends \ITico_core\common_class { 
    
        public function get_info_from_ad($input_id) { 
         $xml_file = parent::get_set('xml'); 
         $ad_info = $xml_file->xpath("//ad[@id='" . $input_id . "']"); 
         parent::get_set('ad_info', $ad_info); 
         return $ad_info; 
        } 
    
    } 
    

    上面的代碼在單元測試時工作,雖然在單元測試中工作,但傳遞的參數在xpath上不工作

    <h2>get_info_from_ad</h2> 
    test data: 1<br> 
    info from ad:- <br> 
    <?php 
    $ad_xml_model->get_info_from_ad(1); 
    $ad_info = $ad_xml_model->get_set('ad_info'); 
    print_r($ad_info); 
    

    但在從控制器被調用時,下面的代碼它不工作

    class main_controller(){ 
        $ad_top_limit = count($ads_from_category); 
        $key = rand(0, $ad_top_limit - 1); 
        $chosen_ad = $ads_from_category[$key]; 
        parent::get_set('chosen_ad', $chosen_ad); 
        $ad_info = $ad_xml_model->get_info_from_ad($chosen_ad); 
        parent::get_set('ad_info', $ad_info); 
        if ($ad_info != null) { 
         switch ($ad_type) { 
          case NUll: 
           break; 
          case 'long': 
           $long_view = new long_view($ad_info); 
           $long_view->show_ad(); 
         } 
        } 
    } 
    

    和調試網頁測試

    <?php 
    echo $main_controller->get_set('chosen_ad') . "<br>"; 
    ?> 
    ad information:-: <br> 
    <?php 
    print_r($main_controller->get_set('ad_info')); 
    

    screenshot of the debug page

    我每次去這種方式呼應所有變量來檢查它們不是null,而是用於有些原因,xpath在從主控制器調用時並不起作用,但它在單元測試中工作正常,即使傳遞完全相同的參數。

    回答

    0

    我找到的解決方案是隱含告訴XPath的是一個int

    public function get_info_from_ad($input_id) { 
        $xml_file = parent::get_set('xml'); 
        $ad_info = $xml_file->xpath("//ad[@id='" . (int)$input_id . "']"); 
        parent::get_set('ad_info', $ad_info); 
        return $ad_info; 
    } 
    

    出於某種原因,如果我將它設置爲一個字符串,它仍然無法正常工作,也許別人可以在此分享光。

    相關問題