2009-12-02 67 views
1

包括我,包括像這樣內部函數變量在PHP

// some function 
function SomeFunction() 
{ 
    $someData = 'SomeData'; 
    include_once('some_file.php'); 
} 

// some_file.php 
<?php echo $someData; ?> 

我將如何得到這個工作,其中包括:文件可以使用變量從調用函數的另一個文件中的函數?我將使用一些輸出緩衝。

回答

2

只要$someDataSomeFunction()定義,some_file.php將不得不$someData訪問。

如果您需要訪問SomeFunction()以外的變量,請將它們作爲參數傳遞給SomeFunction()

+0

它是否必須直接相關?我正在使用'_include_once',它擴展了輸入'include_once'作爲目錄偏移量。 – 2009-12-02 17:37:01

0

最好是不要做使用全局變量所有,但傳遞變量參數:

function SomeFunction() 
{ 
    $someData = 'SomeData'; 
    include_once('some_file.php'); 
    some_foo($someData); 
} 

否則你可能會改變你的代碼庫中的代碼spaghetty,至少在長遠。

+0

我真的不想這樣做。我正在構建一個簡單的視圖引擎。 – 2009-12-02 17:34:34

+0

你的意思是像smarty這樣的模板系統,但更簡單?如果是的話,我會爲你提供合適的解決方案。 – Flavius 2009-12-02 19:02:50

0

似乎有點無組織的,包括函數文件...關於...

function SomeFunction() 
{ 
    $someData = 'SomeData'; 
    return $someData; 
} 

$data = SomeFunction(); 
<?php include('file.php') ?> // file.php can now use $data 
0

你不必做的任何事情。 include()(和它的兄弟姐妹)的用法類似於在include()被調用的位置將包含文件的代碼複製粘貼到包含文件中。

簡單實例

test.php的

<?php 

$foo = 'bar'; 

function test() 
{ 
    $bar = 'baz'; 
    include 'test2.php'; 
} 

test(); 

test2.php

<?php 
echo '<pre>', print_r(get_defined_vars(), 1), '</pre>'; 

再次,這是類似於組合

<?php 

$foo = 'bar'; 

function test() 
{ 
    $bar = 'baz'; 
    echo '<pre>', print_r(get_defined_vars(), 1), '</pre>'; 
} 

test();