PHP中的自动化(PHP中的开始和提交)


Automocity in PHP (Begin and Commit in PHP)

可能听起来很傻,但我想知道是否有任何方法将PHP代码包含在某些函数中,以便如果发生任何错误,它会回滚它所做的所有过程。(就像我们在mysql- Automocity中做的那样)例如:

$this->BEGIN;
$this->function1();
$this->function2();
$this->COMMIT;

数据库服务器可以简单地回滚对数据库表的所有更改,但由于PHP功能强大得多,这无法(轻松地)完成。

你可以这样做:

try
{
    // Do something / create file
    file_put_contents("/tmp/test.txt", "Test");
    // ... some more actions here ...
    // some error occurs, rollback!
    if($some_error)
    {
        throw new Exception();
    }
}
catch(Exception $e)
{
    // undo all changes
    @unlink("/tmp/test.txt");
}

还要注意,有一些事情是不能撤消的。对某些web服务的http调用,例如