2013-03-18 86 views
0

這是我的問題,我在方法中使用靜態變量。我使用for循環來創建新的實例。重新初始化新實例的靜態變量

class test_for{ 

    function staticplus(){ 
     static $i=0; 
     $i++; 
     return $i; 
    } 

    function countplus() { 
     $res = ''; 
     for($k=0 ; $k<3 ; $k++) { 
      $res .= $this->staticplus(); 
     } 
     return $res; 
    } 
} 

for($j=0 ; $j<3 ; $j++) { 
    $countp = new test_for; 
    echo $countp->countplus().'</br>'; 
} 

它返回:

123 
456 
789 

有沒有一種方法創建新實例時初始化靜態變量,所以這是回報:

123 
123 
123 

感謝您的幫助!

+0

看來你所要求的是靜態變量的對立面。相反,你想要一個實例變量。 – Dunes 2013-03-18 09:11:49

回答

0

我不明白爲什麼需要這一點,但可以實現的行爲。 試試這個:

class test_for{ 

protected static $st;  // Declare a class variable (static) 

public function __construct(){ // Magic... this is called at every new 
    self::$st = 0;   // Reset static variable 
} 

function staticplus(){ 
    return ++self::$st; 
} 

function countplus() { 
    $res = ''; 
    for($k=0 ; $k<3 ; $k++) { 
     $res .= $this->staticplus(); 
    } 
    return $res; 
} 
} 

for($j=0 ; $j<3 ; $j++) { 
    $countp = new test_for; 
    echo $countp->countplus().'</br>'; 
} 
+0

爲什麼你讓'$ st'成爲一個靜態變量?它應該是一個簡單的'private $ st = 0',那麼你完全不需要'__constructor()'。 – 2013-03-18 08:18:37

+0

@Michael不一樣,靜態將在所有構造完成後保持設置狀態,並且額外的obj-> countplus()調用會將它設置爲更高的交叉對象(因爲它是一個類var),這是一種奇怪的行爲,但它也是需要我猜。 – Ihsan 2013-03-18 08:21:54

+0

@Michael畢竟,如果你只是想要一個123,你不會在問題的例子中將static $聲明爲static。 – Ihsan 2013-03-18 08:24:19

0

嘗試把你的資源,也許一個靜態變量:

public res 

function countplus() { 
    $this->res = 0; 
    for($k=0 ; $k<3 ; $k++) { 
     $this->res .= $this->staticplus(); 
    } 
    return $this->res; 
} 
+0

不起作用,問題位於靜態變量$ i – LostSEO 2013-03-18 08:16:34