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

谢谢你的帮助!

4

2 回答 2

0

尝试将你的 res 放在一个静态变量中:

public res 

function countplus() {
    $this->res = 0;
    for($k=0 ; $k<3 ; $k++) {
        $this->res .= $this->staticplus();
    }
    return $this->res;
}
于 2013-03-18T08:11:24.727 回答
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>';
}
于 2013-03-18T08:14:46.667 回答