〖PHP中实现ASP中的Application 功能〗
/*
作者: 何志强[hzq@chinaasp.com hhzqq@21cn.com]
主页: http://www.phpchina.com/
ICQ : 50721529
版本: 1.0
未经本人同意,不得以任何方式转载
注意PHP需要有Semaphore and shared memory functions支持:
从源代码安装PHP时,在./configure后面加上--enable-sysvsem和--enable-sysvshm
*/
if(!defined("__Class_Application")){
define("__Class_Application",1,1);
define("Semaphore_Key",1000,1);
define("SharedMem_Key",2000,1);
define("SharedMem_Size",65535,1); //共享内存大小
class Application{
var $SemaphoreID;
var $SharedMemID;
var $VarIndexes;
function Application(){
$this->SemaphoreID = sem_get(Semaphore_Key,1,0600);
$this->SharedMemID = shm_attach(SharedMem_Key,SharedMem_Size,0600);
$this->lock();
$this->VarIndexes = @shm_get_var($this->SharedMemID,0);
if(empty($this->VarIndexes)){
$this->VarIndexes = array();
shm_put_var($this->SharedMemID,0,$this->VarIndexes);
}
$this->unlock();
}
//在对共享内存进行操作前请调用该函数,防止多个进程同时对该共享内存进行操作
function lock(){
sem_acquire($this->SemaphoreID);
}
//在对共享内存操作完后请调用该函数,允许其它进程对该共享内存进行操作
function unlock(){
sem_release($this->SemaphoreID);
}
//取出存在共享内存中的某变量,返回false表示共享内存中无该变量
function read($name){
if(!isset($this->VarIndexes[$name])) return false;
$GLOBALS[$name] = shm_get_var($this->SharedMemID,$this->VarIndexes[$name]);
return true;
}
//读出存在共享内存中的所有变量
function readall(){
reset($this->VarIndexes);
while(list($name,$id)=each($this->VarIndexes))
$GLOBALS[$name] = shm_get_var($this->SharedMemID,$id);
}
//将指定变量存入共享内存
function save($name){
if(!isset($this->VarIndexes[$name])){
$this->VarIndexes[$name] = count($this->VarIndexes)+1;
shm_put_var($this->SharedMemID,0,$this->VarIndexes);
}
shm_put_var($this->SharedMemID,$this->VarIndexes[$name],$GLOBALS[$name]);
}
//保存在共享内存中的所有变量
function saveall(){
reset($this->VarIndexes);
while(list($name,$id)=each($this->VarIndexes)){
if(isset($GLOBALS[$name]))
shm_put_var($this->SharedMemID,$id,$GLOBALS[$name]);
}
}
//清空共享内存中的所有变量
function clear(){
reset($this->VarIndexes);
while(list($name,$id)=each($this->VarIndexes))
shm_remove_var($this->SharedMemID,$id);
$this->VarIndexes = array();
shm_put_var($this->SharedMemID,0,$this->VarIndexes);
}
}
}
?>
/*测试
class ClassTest{
var $name;
function ClassTest($name){
$this->name = $name;
}
}
$App = new Application();
$App->lock();
if($cmd=='clear') $App->clear();
if($App->read('count')) $count++;
else $count = 1;
$App->save('count');
if($App->read('array')){
echo '存放数组测试:
';
for($i=0;$i';
echo '
';
}
else{
$array = array('PHP','JSP','ASP');
$App->save('array');
}
if($App->read('MyClass')){
echo '存放Class测试:
';
echo ' '.$MyClass->name.'
';
echo '
';
}
else{
$MyClass = new ClassTest('何志强');
$App->save('MyClass');
}
$App->unlock();
echo 'this page has been visited '.$count.'
';
echo 'you can restart from here
';
*/
?>
责任编辑: