2017-01-18 21:15
浏览 140


I have seen several answers on object destruction order, and all point out that order is not guaranteed. Since I cannot control the order, I would like to invoke a function after all objects have been destroyed.

register_shutdown_function is invoked prior to object destruction, thus not an option. I have looked at tricks like set_error_handler using the object so it is invoked "late", but that is not sufficient.

Some background on the problem, this is a complex CMS with dozens of separate files for routes (view) layer. There is a common boot include, but not a common one run at shutdown. I am using APCu object caching through a common inherited base class, and need to make sure an object is purged. It is possible that for any two instances of the same object created during a page load, one might want to purge itself, and the other might want to cache itself. Obviously purge trumps all else, so I need to call apc_delete on a global set of cache keys to purge one all __destruct()'ion is complete.

图片转代码服务由CSDN问答提供 功能建议

我见过几个关于对象销毁订单的答案,并且都指出订单无法保证。 由于我无法控制顺序,我想在所有对象被销毁后调用一个函数。

在对象销毁之前调用register_shutdown_function,因此不是一个选项。 我已经使用该对象查看了set_error_handler这样的技巧,因此它被“迟到”调用,但这还不够。

问题的一些背景,这是一个复杂的CMS ,包含许多用于路径(视图)图层的单独文件。 有一个常见的启动包括,但不是在关机时运行的常见启动。 我通过公共继承的基类使用APCu对象缓存,并且需要确保清除对象。 对于在页面加载期间创建的同一对象的任何两个实例,可能希望清除自身,而另一个可能想要自我缓存。 显然purge胜过其他所有,所以我需要在一组全局缓存键上调用apc_delete来清除一个__destruct()'离子完成。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • douchigu1723 2017-01-20 16:38

    As I said in my comment above, the mixed state of multiple object instances sounds like a design flaw. I think you always want all instances of an object to be the latest, or at least not touch the cache if they aren't. I would think your caching and/or object loading layer could handle this.

    To answer your underlying question, I wrote a script to test PHP's shutdown sequence:

    <?php  /* Adapted from https://evertpot.com/160/ */
            function($buffer) {
                return $buffer . "output buffer flushed
        $empty = function() {
            return true;
        $close = function() {
            echo "session close
            return true;
        $write = function() {
            echo "session write
            return true;
        session_set_save_handler($empty, $close, $empty, $write, $empty, $empty);
            function() {
                echo "register_shutdown_function
        class MyClass {
            function __destruct() {
               echo "object destructor
        $myObject = new MyClass;

    The output:

    object destructor
    output buffer flushed
    session write
    session close

    It seems the flush of output buffering and session write/close are 2 places where you know all of your objects have been destroyed. (This also assumes you're not using the newer form of session_set_save_handler that can register itself as a shutdown function.)

    解决 无用
    打赏 举报

相关推荐 更多相似问题