我想知道是否有一种方法可以将更改侦听器之类的东西添加到变量中。我的意思最简单的例子就是沿着这些思路工作;
// Start with a variable
$variable = "some value";
// Define a listener
function myChangeListener($variable) {
// encode with json_encode and send in cookie
}
// Add my listener to the variable
addListenerToVariable(&$variable, 'myChangeListener');
// Change the variables value, triggering my listener
$variable = "new value";
现在您可能会问,为什么我什至需要费心使用这种方法,为什么不创建一个函数来设置 cookie。答案是我有一个&__get($var)
魔术方法可以返回对多维数组元素的引用,我希望使用类似的方法来检测数组元素或其子元素何时/是否已被编辑,然后发送一个cookie(如果有的话)。希望的结果是这样的;
$cookies->testArray["test"] = "newValue";
// This would send the cookie 'testArray' with the value '{"test":"newValue"}'
老实说,我认为这是完全不可能的,如果我是对的,我深表歉意。但是我昨天刚刚学会了如何正确使用引用,所以我想在我完全写下这个想法之前先问问。
感谢我收到的任何回复,无论是我希望的还是我期望的。
编辑:
为了更清楚起见,这是我要完成的示例类;
class MyCookies {
private $cookies = array();
private $cookieTag = "MyTag";
public function __construct() {
foreach($_COOKIE as $cookie => $value) {
if(strlen($cookie)>strlen($this->cookieTag."_")&&substr($cookie,0,strlen($this->cookieTag."_"))==$this->cookieTag."_") {
$cookieVar = substr($cookie,strlen($this->cookieTag."_"));
$this->cookies[$cookieVar]['value'] = json_decode($value);
}
}
}
// This works great for $cookies->testArray = array("testKey" => "testValue");
// but never gets called when you do $cookies->testArray['testKey'] = "testValue";
public function __set($var, $value) {
if(isset($value)) {
$this->cookies[$var]['value'] = $value;
setcookie($this->cookieTag.'_'.$var,json_encode($value),(isset($this->cookies[$var]['expires'])?$this->cookies[$var]['expires']:(time()+2592000)),'/','');
} else {
unset($this->cookies[$var]);
setcookie($this->cookieTag.'_'.$var,'',(time()-(172800)),'/','');
}
return $value;
}
// This gets called when you do $cookies->testArray['testKey'] = "testValue";
public function &__get($var) {
// I want to add a variable change listener here, that gets triggered
// when the references value has been changed.
// addListener(&$this->config[$var]['value'], array(&$this, 'changeListener'));
return $this->config[$var]['value'];
}
/*
public function changeListener(&$reference) {
// scan $this->cookies, find the variable that $reference is the reference to (don't know how to do that ether)
// send cookie
}
*/
public function __isset($var) {
return isset($this->cookies[$var]);
}
public function __unset($var) {
unset($this->cookies[$var]);
setcookie($this->cookieTag.'_'.$var,'',(time()-(172800)),'/','');
}
public function setCookieExpire($var, $value, $expire=null) {
if(!isset($expire)) {
$expire = $value;
$value = null;
}
if($expire<time()) $expire = time() + $expire;
if(isset($value)) $this->cookies[$var]['value'] = $value;
$this->cookies[$var]['expires'] = $expire;
setcookie($this->cookieTag.'_'.$var,json_encode((isset($value)?$value:(isset($this->cookies[$var]['value'])?$this->cookies[$var]['value']:''))),$expire,'/','');
}
}
至于我为什么不想有更新功能,真的只是个人喜好。这将在其他人可以扩展的框架中使用,我认为让他们能够将 cookie 视为单行代码中的变量感觉更流畅。