我有一个聊天机器人,它将一些数据保存到用户发送的数据库中。我想在向用户发送响应后将其保存到数据库(缓慢的网络调用)。
我可以在 Python Tornado 中做到这一点,但我无法在 PHP Apache 中做到这一点。
用户发送输入作为请求 -> 我们处理它 -> 我们将输出作为响应发送给用户 -> 然后我们希望存储数据
class A
{
function __construct()
{
echo "Hello World";
}
function __destruct()
{
sleep(15); //I want this to happen after response is being send
}
function calc()
{
echo "Progress World";
}
}
__destruct
在对象删除、对象超出范围或正常脚本结束时调用。如果脚本没有正常终止而是被杀死,则析构函数可能根本不会被调用。
如果您只想在特定点执行清理任务并确保它们得到处理,请使用 PHP 5.5 引入的
finally
子句
来自 PHP 站点的
__destruct
示例:
<?php
class my_class {
public $error_reporting = false;
function __construct($error_reporting = false) {
$this->error_reporting = $error_reporting;
}
function __destruct() {
if($this->error_reporting === true) $this->show_report();
unset($this->error_reporting);
}
?>
请参阅有关析构函数的 PHP 文档。我希望这有帮助。
PHP 的垃圾收集器和对象销毁是由运行时管理的自动过程,因此您无法直接控制何时调用析构函数。 您可以在异常处理的
finally
块中添加清理功能。
try{
// your code
}catch(Exception $e){
// exception handling
}finally{
//perform cleanup task or destructor here
}