测试程序如下:
function &getObj_ref(){
static $obj;
static $id = 1;
if(empty($obj)){
$obj = new stdClass();
//$obj->name =
get_class($obj);
//$obj->id =
$id++;
$obj->time =
time();
}
return $obj;
}
function getObj(){
static $obj;
static $id = 1;
if(empty($obj)){
$obj = new stdClass();
//$obj->name =
get_class($obj);
//$obj->id =
$id++;
$obj->time =
time();
}
return $obj;
}
function foo() {
static
$a;
$a++;
echo
"$a\n";
unset($a);
}
$obj_ref = getObj_ref();
var_dump($obj_ref);
unset($obj_ref);
var_dump($obj_ref);
$obj_ref2 = getObj_ref();
var_dump($obj_ref2);
echo "-------------\n";
$obj = getObj();
var_dump($obj);
unset($obj);
var_dump($obj);
$obj2 = getObj();
var_dump($obj2);
echo "-------------\n";
foo();
foo();
foo();
得到的结果如下:
X-Powered-By: PHP/5.2.10 ZendServer
Set-Cookie:
ZendDebuggerCookie=127.0.0.1%3A10137%3A0||084|77742D65|1015;
path=/
Content-type: text/html
object(stdClass)#1 (1) {
["time"]=>
int(1274961151)
}
NULL
object(stdClass)#1 (1) {
["time"]=>
int(1274961151)
}
-------------
object(stdClass)#2 (1) {
["time"]=>
int(1274961151)
}
NULL
object(stdClass)#2 (1) {
["time"]=>
int(1274961151)
}
-------------
1
2
3
程序和对应的结果分成三部分:返回静态变量的引用,返回静态变量,在函数内部unset;
getObj_ref函数和getObj函数虽然是两个不同的函数,但是它们的静态局部变量竟然是同一个对象。
这应该是PHP优化的结果。也可能是个BUG。从外部unset都没有用,静态变量仍然在那,下次调用
此函数的时候,返回的仍然是那个变量。
而foo函数内部unset也是没用的,$a的值仍然保留,以至于下次调用foo函数的时候,得到了增加的值。
可见unset是无法删除静态变量的。
这可能是个BUG吗?