2013-03-18 81 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