PHP在数组改变时运行函数


PHP Run Function on Array Change

如何在数组更改时运行函数?例如,每当我读取,写入或使用数组($_SESSION)时,我想运行一个函数(它将在会话数组中设置一个变量,但我不希望它也运行函数)。

我需要这样做,因为我计划创建一个时间戳,每当使用数组$_SESSION时更新它。这可能吗?

例如:

session_start();
$_SESSION["foo"] = "bar"; //run the function!
$foo = $_SESSION["foo"]; //run the function! (optional, though preferred)

函数应该是这样的:

$_SESSION["timestamp"] = time();  //do not run the function!

谢谢你的建议!

您可以使用一个基本类来包裹$_SESSION。下面是一个简单的例子,使用__set()__get()魔术方法拦截设置您的值。

注意,我使用了一个类属性$this->_SESSION,因为codepad不允许我使用一个真正的会话。

<?php
class SessionSetting {
    private $_SESSION = array();
    function __set($name, $value) {
        $this->_SESSION[$name] = $value;
        $this->value_saved($name, $value);
    }
    function __get($name) {
        $this->value_accessed($name);
        return $this->_SESSION[$name];
    }
    function value_saved($name, $value) {
        echo "'$_SESSION['$name'] set to '$value''n";
    }
    function value_accessed($name) {
        echo "'$_SESSION['$name'] accessed ({$this->_SESSION[$name]})'n";
    }
}
$ss = new SessionSetting;
$ss->prop1 = 'test';
$ss->prop2 = 'test';
echo "$ss->prop1'n";
echo "$ss->prop2'n";
?>
http://codepad.org/98p3uakc

生产:

$_SESSION['prop1'] set to 'test'
$_SESSION['prop2'] set to 'test'
$_SESSION['prop1'] accessed (test)
test
$_SESSION['prop2'] accessed (test)
test

不确定你想做什么,但这是可能的ArrayAccess

class ArrayThing implements 'ArrayAccess{
  protected $data = array();
  public function offsetExists($key){
    return array_key_exists($this->data, $key);
  }   
  // $foo = $_SESSION["foo"];
  public function offsetGet($key){
    // run your function    
    return $this->data[$key];
  }
  // $_SESSION["foo"] = "bar";
  public function offsetSet($key, $value){
    // if($key != 'timestamp')
    //   run your function ?
    $this->data[$key] = $value;
  }  
  public function offsetUnset($key){
    unset($this->data[$key]);  
  }    
}
$_SESSION = new ArrayThing();

我应该提到,如果你想让它像会话超全局变量一样工作,你可能需要在完成后将对象转换为数组(并在构造函数中导入会话内容)。