__destruct 运行 本身还是我需要使用 unset() 或 register_shutdown_function() 才能使其工作
Does __destruct run by itslef or do I need to use unset() or register_shutdown_function() in order for it to work
a) 是否 __destruct 运行 每次处理代码时,仅由其本身
b) 或者,不,您需要使用 unset($objectName) 才能使其 运行 (另一个选项是 register_shutdown_function() )。
c) 还有其他方面与此相关吗?就像它在这个或那个时候自己工作一样,你也可以使用这个或那个来 运行,任何东西......
不,unset()
函数不是调用__destruct()
的唯一方法。根据 documentation,“只要没有对特定对象的其他引用,或在关闭序列期间以任何顺序调用析构函数方法”。
为了说明这一点,请考虑以下方法,当 __destruct()
将被自动调用时 :
1) 当class实例没有赋值给任何变量时立即调用:
<?php
new TheClass(); #-> this line calls __destruct()
/* More PHP Code */
?>
2) 脚本执行停止时调用:
<?php
$obj = new TheClass();
exit; #-> this line calls __destruct()
/* More PHP Code */
?>
3) 当unset()
销毁class:
的引用时调用
<?php
$obj = new TheClass();
unset($obj); #-> this line calls __destruct()
/* More PHP Code */
?>
4) 变量值重新赋值时调用:
<?php
$obj = new TheClass();
$obj = 'any value'; #-> this line calls __destruct()
/* More PHP Code */
?>
5) 当脚本完成执行时调用:
<?php
$obj = new TheClass();
/* More PHP Code */
#-> this line calls __destruct()
?>
6) 退出变量作用域时调用:
<?php
call_user_func(function() {
$obj = new TheClass();
/* More PHP Code */
return true; #-> this line calls __destruct()
});
/* More PHP Code */
?>
a) 是否 __destruct 运行 每次处理代码时,仅由其本身
b) 或者,不,您需要使用 unset($objectName) 才能使其 运行 (另一个选项是 register_shutdown_function() )。
c) 还有其他方面与此相关吗?就像它在这个或那个时候自己工作一样,你也可以使用这个或那个来 运行,任何东西......
不,unset()
函数不是调用__destruct()
的唯一方法。根据 documentation,“只要没有对特定对象的其他引用,或在关闭序列期间以任何顺序调用析构函数方法”。
为了说明这一点,请考虑以下方法,当 __destruct()
将被自动调用时 :
1) 当class实例没有赋值给任何变量时立即调用:
<?php
new TheClass(); #-> this line calls __destruct()
/* More PHP Code */
?>
2) 脚本执行停止时调用:
<?php
$obj = new TheClass();
exit; #-> this line calls __destruct()
/* More PHP Code */
?>
3) 当unset()
销毁class:
<?php
$obj = new TheClass();
unset($obj); #-> this line calls __destruct()
/* More PHP Code */
?>
4) 变量值重新赋值时调用:
<?php
$obj = new TheClass();
$obj = 'any value'; #-> this line calls __destruct()
/* More PHP Code */
?>
5) 当脚本完成执行时调用:
<?php
$obj = new TheClass();
/* More PHP Code */
#-> this line calls __destruct()
?>
6) 退出变量作用域时调用:
<?php
call_user_func(function() {
$obj = new TheClass();
/* More PHP Code */
return true; #-> this line calls __destruct()
});
/* More PHP Code */
?>