2015-11-06 80 views
-1

我想在foreach循環中包含外部文件,並且能夠讀取該外部php文件中的foreach循環變量。請參閱下面的代碼:如何在foreach循環中包含/需要外部文件並能夠讀取循環的變量?

$ProductPDSLink = ''; 

foreach($item->ProductRangeName as $rangeName){ 

    include($App_URL . '/Handler/_PDSSwitcherHandler.php'); 

} 

而且在包括外部PHP文件代碼如下:

global $rangeName; 
global $ProductPDSLink; 
switch ($rangeName) { 
    case 'Insurance': 
     $ProductPDSLink .= "LInk"; 
     break; 
    case 'Priority Protection': 
     $ProductPDSLink .= "Link2"; 
     break; 
    case 'Life Solutions': 
     $ProductPDSLink .= "Link 3"; 
     break; 
} 

最後我嘗試呼應它,但沒有顯示出來。

echo $ProductPDSLink; 

在此先感謝。

+0

你可以編輯你的帖子提供代碼,你嘗試'回聲'它? – Arc676

+0

爲什麼不創建一個類而不是包含整個文件? – roullie

+0

重新roullie,foreach($ item-> ProductRangeName作爲$ rangeName)也在另一個foreach循環中。 – Mike

回答

0

我設法解決這個問題,謝謝你的提示。

我在類中創建了一個類和函數,然後將函數解析到循環中。所以下面的代碼:

在包含文件中:

class PDS{ 
    public static function functionName(){ 
     global $rangeName; 
     global $ProductPDSLink; 
     switch ($rangeName) { 
     case 'Insurance': 
      $ProductPDSLink .= "LInk"; 
      break; 
     case 'Priority Protection': 
      $ProductPDSLink .= "Link2"; 
      break; 
     case 'Life Solutions': 
      $ProductPDSLink .= "Link 3"; 
      break; 
    } 
    } 
} 

然後我包括文件然後使用$ PDS = PDS新解析它們在環(); $ ProductPDSLink。= functionName($ rangeName);

現在它工作!