2012-07-03 43 views
0

我有2個PHP文件。PHP變量穿越require_once和函數

的index.php:

<?php 
    $counter = 0; 
    require_once('temp.php'); 
    temp(); 
    echo $counter; 
?> 

temp.php:

<?php 
    function temp() { 
      tempHelper(); 
    } 
    function tempHelper() { 
      $counter++; 
    } 
?> 

我想打印1不是0 我試圖$計數器設置沒有成功全局變量。

我該怎麼辦?

回答

2

您的tempHelper函數正在遞增本地$counter變量,而不是全局變量。你必須按引用過這兩個函數傳遞變量,或者使用全局變量:

function tempHelper() { 
    global $counter; 
    $counter++; 
} 

需要注意的是全局變量的依賴可能表明應用程序中的設計缺陷。

+0

:)這裏

更多信息的鏈接http://php.net/manual/en/language.variables.scope.php –

+0

沒有方式中的初始化設置$櫃檯讓他成爲全球? – Nir

+0

在PHP中,沒有辦法讓用戶定義[超級全局](http://php.net/manual/en/language.variables.superglobals.php)。如果您想要這樣做,請重新考慮您的應用程序設計。 –

1

我會建議不要使用全局變量。爲你的櫃檯使用類可能會更好。

class Counter { 
    public $counter; 

    public function __construct($initial=0) { 
     $this->counter = $initial; 
    } 

    public function increment() { 
     $this->counter++; 
    } 

} 

或者只是使用一個變量沒有的功能。你的函數似乎是多餘的,因爲輸入$counter++比函數名稱更容易。

0

我想這應該工作:

<?php 
    $counter = 0; 

    function temp() { 
      // global $counter; [edited, no need for that line] 
      tempHelper(); 
    } 
    function tempHelper() { 
      global $counter; 
      $counter++; 
    } 

    temp(); 
    echo $counter; 
?> 

或者你可以傳遞變量作爲自變量或者從函數返回新值。在比我更快http://www.simplemachines.org/community/index.php?topic=1602.0

+0

沒有理由在'temp'內部聲明'global $ counter',它不使用它。 – meagar

+0

我現在才意識到它。謝謝。 –

+0

臨時函數似乎是多餘的。 –