Heim  >  Artikel  >  php教程  >  php静态变量define,static,const

php静态变量define,static,const

WBOY
WBOYOriginal
2016-06-13 11:18:461020Durchsuche

 

静态变量只存在于函数作用域内,也就是说,静态变量只存活在栈中。一般的函数内变量在函数结束后会释放,比如局部变量,但是静态变量却不会。就是说,下次再调用这个函数的时候,该变量的值会保留下来

最简单定义方法

define() 函数定义一个常量。

常量类似变量,不同之处在于:

在设定以后,常量的值无法更改
常量名不需要开头的美元符号 ($)
作用域不影响对常量的访问
常量值只能是字符串或数字
语法

define(name,value,case_insensitive)

class foo {
   static $my_static = 5;
   public $my_prop = 'bla';
}

print foo::$my_static; copyright dedecms
$obj = new foo;
print $obj->my_prop;
?>

const 是常量,即从程序运算开始到结束,数值不变的量。

class say_const{  
const charset=”中国”;  
publice function say_hello(){  
echo slef::charset;  
}  
}  
$const1=new say_const()’  
$const1->say_hello();  
?>  

输出就是“中国”

下面一款完整的静态变量

function write_file($file,$msg,$usecheck=5){
 static $check=1;//这里用到了~
 $f=@fopen($file,"a+b");
 if($f){
  if(flock($f,lock_ex)){
   fwrite($f,$msg);
   flock($f,lock_un);
   fclose($f);
  }else{
   fclose($f);
   $check++;
   if($check     sleep(1);//暂停下程序,等其他进程释放该资源
    write_file($file,$msg);
   }
  }
 }else{
  $check++;
  if($check    sleep(1);//暂停下程序,等其他进程释放该资源
   write_file($file,$msg);
  }
 }
}


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn