複製代碼 代碼如下:
<?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);
}
}
?>