保存在析构函数中 - 坏主意?
在 PHP 应用程序中,在对象的析构函数期间运行我的保存代码会是一个坏主意吗?我之所以这么问,是因为如果可以的话,我可以在父 Model 类的析构函数中添加一个 save()
调用,这样我就不用再记住其他地方了。
我知道这样做确实有效,因为我有一个完整的应用程序(尽管写得不好)在上面运行。但有充分的理由不这样做吗?
In a PHP app, would it be a bad idea to run my saving code during an object's destructor? I ask because if it's ok then I could add a save()
call in the destructor of the parent Model class and save myself the trouble of remembering anywhere else.
I know that doing this does work, as I have an entire app (albeit a poorly written one) running on it. But are there good reasons not to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不保证以任何顺序调用析构函数。如果您的页面正在卸载并且所有对象讲师开始被调用,会发生什么情况。您永远不知道需要使用的数据库对象是否仍然有效,或者是否已被卸载。
The destructor is not guaranteed to be called in any order. What happens if your page is unloading and all the objects instructors start to get called. you never know if the database object you need to use is still valid, or if it has been unloaded.
实际上,PHP 会尝试以正确的顺序销毁对象,因此它是相当安全的(考虑到如果您尝试保存某些内容,则意味着您仍在保留对它的引用)。您需要注意的是,即使存在捕获,在析构函数期间引发异常也会导致致命错误。你可以玩例子,正常引用并不容易让 PHP 失败,这里有一个简单的方法让 PHP 疯狂地使用析构函数,所以它不知道如何结束它们,但正如我所说,这不是你通常会发现的东西在你的代码中:
Actually, PHP will try to destroy objects in the right order, so it is quite safe (considering if you're trying to save something, it means you are still hodling a reference to it). What you need to be aware of is that throwing an exception during a destructor will cause a fatal error even if there's a catch. You can play with examples, and it's not easy to make PHP fail with normal referencing, here's a simple way to make PHP crazy with destructors so it doesn't know how to end them, but as I said, it's not something you normally find in your code:
IMO,将此类功能添加到析构函数中并不是最佳选择。对我来说非常重要的原因之一是代码复杂性增加和可读性降低。第三个刚接触该项目的人最终会花费相当多的时间来弄清楚发生了什么。
话虽如此,无论理论上是好是坏,都取决于所采用的编程逻辑。如果相关类将在后期扩展,那么析构函数中的 save() 可能会给您带来一些麻烦;再次取决于您想要实现的目标。
IMO, adding such functionality into the destructor is not the best choice. The reason, one very important to me, is increased code complexity and reduced readability. A third person new to the project will end-up spending quite a bit of time figuring out whats been happening.
Having said that, whether it is theoretically good or bad, its down to the programming logic being employed. If the class in question would be extended at a latter stage, then the save() in your destructor might give you some grief; again depends on what you are trying to achieve.