2012-01-04 123 views
0

我有一個三層樹顯示頁面上的內容。它使用includes來顯示基於URL的特定PHP頁面。不會發生的是變量在包含的PHP文件中不被理解。難以傳遞變量通過包括使用全局變量

的index.php

// example url http://fakesite.com/?color=red&user=999 
$user = $_GET['user']; 

if ($_GET['color'] == 'red')   
     {$color = 'red';} 
elseif ($_GET['color'] == 'white')  
     {$color = 'white';} 
else 
     {$color = 'blue';} 

global $color; 
global $user; 
include 'page2.php'; 

使page2.php

global $color; 
global $user; 
echo 'hi '.$user.'I hear you like '.$color; 
+0

我注意到你已經使用'include_once()的'。你有沒有在代碼的早些時候在其他地方加入'page2.php'? – 2012-01-04 05:31:08

+0

@邁克爾沒有,我改變它以防止更多的混淆。 – Tiny 2012-01-04 05:34:20

回答

3

沒有必要在所有的這些$global線。在主腳本中定義的任何變量都在include d文件中定義。這基本上就像把代碼中include d文件,並在include調用的地方順手把它(只有少數例外)

+0

還沒有任何通過。 – Tiny 2012-01-04 05:35:19

0

這條線:

include_once 'page2.php; 

應更改爲:

include_once 'page2.php'; 

你有一個缺少的報價。

0

你有沒有嘗試刪除所有這四個全局線?我不知道這是否是問題,但他們根本沒有必要!

當包含或需要文件時,上面聲明的所有變量都可用於包含的/必需的文件。

如果這沒有解決它,也許你有包括錯誤的路徑。

+0

包含作品。 page2只是無法識別索引中的變量。 – Tiny 2012-01-04 06:29:30

0

的index.php

<?php 
    $user = $_GET['user']; 

    if ($_GET['color'] == 'red')   
      {$color = 'red';} 
    elseif ($_GET['color'] == 'white')  
      {$color = 'white';} 
    else 
      {$color = 'blue';} 
    include 'page2.php'; 
?> 

使page2.php

<?php 
    echo 'hi '.$user.'I hear you like '.$color; 
?> 

全球例如

function dosomethingfunky(){ 
    global $user, $color; 
    echo 'hi '.$user.'I hear you like '.$color; 
}