復制代碼 代碼如下:
<?php
/**
* 功能:實現像JSP,ASP裡Application那樣的全局變量
* author: [url]www.itzg.net[/url]
* version: 1.0
* 版權:如許轉載請保留版權聲明
*/
/*+----------------example----------------------
require_once("Application.php");
$arr = array(0=>"Hi",1=>"Yes");
$a = new Application();
$a->setValue("t1","arui");
$a->setValue("arr",$arr);
$u = $a->getValue();
---------------------------------------------+*/
class Application
{
/**保存共享變量的文件*/
var $save_file = 'Application/Application';
/**共享變量的名稱*/
var $application = null;
/**序列化之後的數據*/
var $app_data = '';
/**是否已經做過setValue的操作 防止頻繁寫文件操作*/
var $__writed = false;
/**
* 構造函數
*/
function Application()
{
$this->application = array();
}
/**
* 設置全局變量
* @param string $var_name 要加入到全局變量的變量名
* @param string $var_value 變量的值
*/
function setValue($var_name,$var_value)
{
if (!is_string($var_name) || empty($var_name))
return false;
if ($this->__writed)
{
$this->application[$var_name] = $var_value;
return;
}
$this->application = $this->getValue();
if (!is_array($this->application))
settype($this->application,"array");
$this->application[$var_name] = $var_value;
$this->__writed = true;
$this->app_data = @serialize($this->application);
$this->__writeToFile();
}
/**
* 取得保存在全局變量裡的值
* @return array
*/
function getValue()
{
if (!is_file($this->save_file))
$this->__writeToFile();
return @unserialize(@file_get_contents($this->save_file));
}
/**
* 寫序列化後的數據到文件
* @scope private
*/
function __writeToFile()
{
$fp = @fopen($this->save_file,"w");
@fwrite($fp,$this->app_data);
@fclose($fp);
}
}
?>