2016-02-26 63 views
0

我環顧四周,但無法找到任何東西。我嘗試使用全局,但我認爲我錯了。如何在不傳遞函數的情況下訪問函數中的變量?

function testing() { 
    $a = (object) array('a' => 100, 'b' => 200); 
    function test2(){ 
     global $a; 
     var_dump($a); 
    } 
    test2(); 
} 
testing(); 

我希望能夠在不傳遞變量作爲參數的情況下獲得$ test2()。編輯: 感謝您的意見和解答。然而,這個例子在我的具體情況下工作似乎並不奏效。我在我的視圖頂部寫了這個小函數,然後在需要時調用它。

var_dump($data); // DATA here is fine - I need it in the function 
function getDataVal($data_index) { 
    return (isset($data->{$data_index}))?$data->{$data_index}:''; 
} 

我那麼晚了一點稱它爲頁面上是這樣的:

<input type="text" id="something" value="<?=getDataVal('something')?>" /> 

我知道我可以只通過$數據的請求,但是我希望有一個更簡單的方法來訪問該函數中的數據。

+0

因爲變量不是全局命名空間,它在第一功能。在兩個函數中定義它是全局的,或者查看下面的鏈接。 – Qirel

+3

看到這個職位:http://stackoverflow.com/questions/4938170/accessing-a-variable-defined-in-a-parent-function –

+0

在這兩個函數中定義爲全局 –

回答

1

全球的意思是 「全球性」,例如一個在全局命名空間中定義的變量。

我不知道爲什麼你試圖避免傳遞變量作爲參數。我的猜測是:它應該是可寫的,而且通常不是。

這些都是同一個解決方案的兩個變種:

<?php 


// VARIANT 1: Really globally defined variable 
$a = false; // namespace: global 

function testing1() { 
    global $a; 
    $a = (object) array('a' => 100, 'b' => 200); 

    function test1(){ 
     global $a; 
     echo '<pre>'; var_dump($a); echo '</pre>'; 
    } 
    test1(); 
} 
testing1(); 


// VARIANT 2: Passing variable, writeable 
function testing2() { 
    $a = (object) array('a' => 100, 'b' => 200); 

    function test2(&$a){ // &$a: pointer to variable, so it is writeable 
     echo '<pre>'; var_dump($a); echo '</pre>'; 
    } 
    test2($a); 
} 
testing2(); 


} 
testing(); 

結果,這兩種型號:

object(stdClass)#1 (2) { 
    ["a"]=> int(100) 
    ["b"]=> int(200) 
} 

object(stdClass)#2 (2) { 
    ["a"]=> int(100) 
    ["b"]=> int(200) 
} 
+0

感謝您花時間回答我的問題。我更新了我的問題。 – Chris

0

把它定義爲全局變量:

a = array(); 
    function testing() { 
     global $a; 
     $a = (object) array('a' => 100, 'b' => 200); 
     function test2(){ 
      global $a; 
      var_dump($a); 
     } 
     test2(); 
    } 

testing(); 

編輯缺少$在global a

相關問題