将变量的值保存在函数中,直到下次函数调用


save value of variable in function till the next time function calls

我需要一些函数或解决方案来保存函数中的变量值,直到下次调用函数而不连接到MySQL。

function test($price){
    if(isset($lastPrice)){
          if($lastPrice>$price){
                    return true;
              }
          $lastPrice = $price; 
         }else{
               $lastPrice = $price;
               returne false;
     }
}
$prices= array ( '1' => '2000',
                 '2' => '2100',
         '3' => '2100'
);
foreach($prices as $key = > $price){
    if($this->test($price)){
         echo 'got expensive';
    }
}

在此代码中,我需要保存$lastPrice直到下次 test() 调用 foreach 时,...

function test($price){ () {
  static $lastPrice;
  ...

试试这个:

$lastPrice = 0;//declaring as global
function test($price){
    if($lastPrice != 0){
          if($lastPrice>$price){
                    return true;
              }
          $lastPrice = $price; 
         }else{
               $lastPrice = $price;
               returne false;
     }
}
$prices= array ( '1' => '2000',
                 '2' => '2100',
         '3' => '2100'
);
foreach($prices as $key = > $price){
    if($this->test($price)){
         echo 'got expensive';
    }
}