2016-07-22 82 views
0

我想找出一種方法將非全局變量傳遞給包含的文檔。PHP模板和變量範圍

page1.php中

function foo() 
{ 
    $tst =1; 
    include "page2.php"; 
} 

使page2.php

echo $tst; 

我怎麼能作出這樣的變量是可見的?以及我將如何做這個PHP模板,所以我可以分開頁面正文和頁腳的HTML頁面。就像在wordpress它有自定義的WP功能,但我沒有看到他們宣佈外部文件使用它們。

非常感謝提前。

+1

'page2.php'必須包含'page1.php',而不是其他方式或只是使用會話變量 –

回答

1

我想你並不完全瞭解發生了什麼。第1頁可能應該做迴應。所以你包括第2頁,foo功能現在可用。您需要調用它才能真正執行。使用global關鍵字將一個全局變量帶入函數範圍。然後你可以迴應它。

第1頁:

include "page2.php"; 
foo(); 
echo $test; 

第2頁:

function foo() 
{ 
    global $test; 
    $test =1; 

} 
0

變量的函數都沒有看到他們的外面時,他們不是全局性的。但是應該在第二個文件中看到函數中的include。

$test="Big thing"; 
echo "before testFoo=".$test; 

// now call the function testFoo(); 

testFoo(); 

echo "after testFoo=".$test; 
Result : *after testFoo=Big thing* 

function testFoo(){ 

    // the varuiable $test is not known in the function as it's not global 

    echo "in testFoo before modification =".$test; 

    // Result :*Notice: Undefined variable: test in test.php 
    // in testFoo before modification =* 

    // now inside the function define a variable test. 

    $test="Tooo Big thing"; 
    echo "in testFoo before include =".$test; 

    // Result :*in testFoo before include =Tooo Big thing* 

    // now including the file test2.php 

    include('test2.php'); 

    echo "in testFoo after include =".$test; 

    // we are still in the function testFoo() so we can see the result of test2.php 
// Result :in testFoo after include =small thing 

    } 

在test2.php

echo $test; 
/* Result : Tooo Big thing 
    as we are still in testFoo() we know $test 
    now modify $test 
*/ 
$test = "small thing"; 

我希望做的事情更加清楚。