2012-10-28 62 views
-2

在PHP中使用「靜態」時出現問題。這裏是我的代碼:PHP中使用靜態作用域變量的未定義變量

static $a = 12; 
if(0) { 
static $b = 11; 
static $a = 11111; 
} 
echo $a.'----------'.$b; 

爲什麼輸出是「11111 ----------」,並獲得「注意:未定義的變量:B」

+4

那麼問題是什麼? – erisco

+1

你確定你使用'static'請參閱http://php.net/manual/en/language.oop5.static.php – DarthVader

+0

@DarthVader技術上的工作...... –

回答

2

它必須是一個範圍的問題,但我不確定爲什麼因爲它不在函數中。無論哪種方式,我得到了它的工作是這樣的:

static $a = 12; 
static $b; // <-- notice this 
if (0) { 
    static $b = 11; 
    static $a = 11111; 
} 
echo $a.'----------'.$b; 
+0

當然它與範圍有關。 – DarthVader

+0

@DarthVader但是爲什麼?這不是一個函數..這必須是一些隱藏的「功能」的PHP,我不知道。 –

+0

不,它不是。如果你在你的'if'中定義了$ b,那麼你不能在所有語言中使用它。 – DarthVader

0

作爲解決您的問題,請參見下面的代碼片斷

<?php 
    static $a = 12; 
    static $b ; 
    if(0) { 
     static $b = 11; 
     static $a = 11111; 
     } 

    echo $a.'----------'.$b; 
    ?> 

在上面的代碼片斷變量$ B如果塊中被定義。一個在條件或循環塊中定義的變量只能在該塊中訪問,所以它需要全局聲明,那麼只有它可以在全局範圍內訪問

+1

您可能想閱讀[this](http://www.php.net/manual/en/language.variables.scope.php#105925)。儘管看起來靜態變量是個例外。 –