用php实现像JSP,ASP里Application那样的全局变量

yipeiwu_com6年前PHP代码库
复制代码 代码如下:


<?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);
 }
}

?> 

相关文章

PHP数组 为文章加关键字连接 文章内容自动加链接

复制代码 代码如下: <?php $keys =array( array('网页特效','/js_a/js.html'), array('seo','/seo/seo.html')...

PHP生成随机字符串实例代码(字母+数字)

当我们要生成一个随机字符串时,总是先创建一个字符池,然后用一个循环和mt_rand()或rand()生成php随机数,从字符池中随机选取字符,最后拼凑出需要的长度 function...

php简单随机字符串生成方法示例

本文实例讲述了php简单随机字符串生成方法。分享给大家供大家参考,具体如下: <?php function rand_str($length,$p='all'){ $...

UCenter中的一个可逆加密函数authcode函数代码

复制代码 代码如下: function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) { $ckey_...

PHP设计模式之原型模式定义与用法详解

本文实例讲述了PHP设计模式之原型模式定义与用法。分享给大家供大家参考,具体如下: 原型设计模式(Prototype Design Pattern)很有意思, 因为它使用了一种克隆技术来...