jjzjj

php - __destruct() 和 __call() 创建无限循环

coder 2024-04-28 原文

我大大简化了我的代码,但我正在做的是这样的:

class App{

    protected $apps = [];

    public function __construct($name, $dependencies){
        $this->name = $name;

        $apps = [];
        foreach($dependencies as $dependName){
            $apps[$name] = $dependName($this); // returns an instance of App
        }
        $this->apps = $apps;
    }

    public function __destruct(){
        foreach($this->apps as $dep){
            $result = $dep->cleanup($this);
        }
    }

    public function __call($name, $arguments){
        if(is_callable([$this, $name])){
            return call_user_func_array([$this, $name], $arguments);
        }
    }
}


function PredefinedApp(){
    $app = new App('PredefinedApp', []);

    $app->cleanup = function($parent){
        // Do some stuff
    };
    return $app;
}

然后我创建一个这样的应用:

$app = new App('App1', ['PredefinedApp']);

它创建一个 App 实例,然后数组中的项目创建新的应用程序实例,无论其定义是什么,并将它们放入内部应用程序数组。

当我在主应用程序上执行我的析构函数时,它应该在所有子应用程序上调用 cleanup()。但正在发生的事情是,它正在执行一个无限循环,我不确定为什么。

我确实注意到,如果我注释掉 call_user_func_array 那么 __call() 只会被调用一次,但它不会执行实际的 closure 然后。

我还注意到,如果我在 __call() 中执行 var_dump(),它会无休止地转储。如果我在 cleanup() 中执行 var_dump() 而不是我得到一个 http 502 错误。

最佳答案

那么让我们通过代码看看这里发生了什么以及为什么:

01|    class App{ 
02|
03|        protected $apps = [];
04|
05|        public function __construct($name, $dependencies){
06|            $this->name = $name;
07|
08|            $apps = [];
09|            foreach($dependencies as $dependName){
10|                $apps[$name] = $dependName($this);
11|            }
12|            $this->apps = $apps;
13|        }
14|
15|        public function __destruct(){
16|            foreach($this->apps as $dep){
17|                $result = $dep->cleanup($this);
18|            }
19|        }
20|
21|        public function __call($name, $arguments){
22|            if(is_callable([$this, $name])){
23|                return call_user_func_array([$this, $name], $arguments);
24|            }
25|        }
26|    }
27|	
28|    function PredefinedApp(){
29|        $app = new App('PredefinedApp', []);
30|
31|        $app->cleanup = function($parent){
32|            //Do stuff like: echo "I'm saved";
33|        };
34|        return $app;
35|    }
36|		
37|    $app = new App('App1', ['PredefinedApp']);

注意:为代码的每一行添加了行号,因此我可以在下面的答案中引用这些行

问题

  1. 您使用以下行创建了一个实例:App:

    $app = new App('App1', ['PredefinedApp']);  //Line: 37
  2. The constructor gets called:

    public function __construct($name, $dependencies){ /* Code here */ }  //Line: 05

    2.1. Following parameters are passed:

    • $name = "App1"
    • $dependencies = ["PredefinedApp"]
  3. You assign $name to $this->name with this line:

    $this->name = $name;  //Line: 06
  4. You initialize $apps with an empty array:

    $apps = [];  //Line: 08
  5. Now you loop through each element of $dependencies, which has 1 element here (["PredefinedApp"])

  6. In the loop you do the following:

    6.1 Assign the return value of a function call to an array index:

    $apps[$name] = $dependName($this);  //Line: 10
    //$apps["App1"] = PredefinedApp($this);

  7. You call the function:

    PredefinedApp(){ /* Code here */}  //Line: 28
  8. Now you create again a new instance of: App in PredefinedApp() same as before (Point 2 - 6, expect in the constructor you have other variable values + you don't enter the loop, since the array is empty)

  9. You assign a closure to a class property:

    $app->cleanup = function($parent){  //Line: 31
        //Do stuff like: echo "I'm saved";
    };
  10. You return the new created object of App:

    return $app;  //Line: 34
  11. Here already the __destruct() gets called, because when the function ends the refcount goes to 0 of that zval and __destruct() is triggered. But since $this->apps is empty nothing happens here.

  12. The new created object in that function gets returned and assigned to the array index (Note: We are back from the function to point 6.1):

    $apps[$name] = $dependName($this);  //Line: 10
    //$apps["App1"] = PredefinedApp($this);

  13. The constructor ends with assigning the local array to the class property:

    $this->apps = $apps;  //Line: 12
  14. Now the entire script ends (We have done line: 37)! Which means for the object $app the __destruct() is triggered for the same reason as before for $app in the function PredefinedApp()

  15. Which means you now loop through each element from $this->apps, which only holds the returned object of the function:

    public function __destruct(){  //Line: 15
        foreach($this->apps as $dep){
            $result = $dep->cleanup($this);
        }
    }
    Array(
        "App1" => App Object
            (
                [apps:protected] => Array
                    (
                    )
    
                [name] => PredefinedApp
                [cleanup] => Closure Object
                    (
                        [parameter] => Array
                            (
                                [$parent] => <required>
                            )
    
                    )
    
            )
    )
    
  16. 对于每个元素(这里只有 1 个)你执行:

    $result = $dep->cleanup($this);  //Line: 17

    But you don't call the closure! It tries to call a class method. So there is no cleanup class method, it's just a class property. Which then means __call() gets invoked:

    public function __call($name, $arguments){  //Line: 21
        if(is_callable([$this, $name])){
            return call_user_func_array([$this, $name], $arguments);
        }
    }
  17. The $arguments contains itself ($this). And is_callable([$this, $name]) is TRUE, because cleanup is callable as closure.

  18. So now we are getting in the endless stuff, because:

    return call_user_func_array([$this, $name], $arguments);  //Line: 23

    Is executed, which then looks something like this:

    return call_user_func_array([$this, "cleanup"], $this);

    Which then again tries to call cleanup as a method and again __call() is invoked and so on...

So at the end of the entire script the hole disaster starts. But I have some good news, as complicated this sounds, the solution is much simpler!

Solution

Just change:

return call_user_func_array([$this, $name], $arguments);  //Line: 23

with this:

return call_user_func_array($this->$name, $arguments);
                           //^^^^^^^^^^^ See here

因为像这样更改它,您不会尝试调用方法,而是调用闭包。所以如果你也把:

echo "I'm saved";

在闭包中分配它时,您将得到输出:

I'm saved

关于php - __destruct() 和 __call() 创建无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32158883/

有关php - __destruct() 和 __call() 创建无限循环的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  3. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  4. ruby - 在 Ruby 中实现 `call_user_func_array` - 2

    我怎样才能完成http://php.net/manual/en/function.call-user-func-array.php在ruby中?所以我可以这样做:classAppdeffoo(a,b)putsa+benddefbarargs=[1,2]App.send(:foo,args)#doesn'tworkApp.send(:foo,args[0],args[1])#doeswork,butdoesnotscaleendend 最佳答案 尝试分解数组App.send(:foo,*args)

  5. ruby - 树顶语法无限循环 - 2

    我脑子里浮现出一些关于一种新编程语言的想法,所以我想我会尝试实现它。一位friend建议我尝试使用Treetop(Rubygem)来创建一个解析器。Treetop的文档很少,我以前从未做过这种事情。我的解析器表现得好像有一个无限循环,但没有堆栈跟踪;事实证明很难追踪到。有人可以指出入门级解析/AST指南的方向吗?我真的需要一些列出规则、常见用法等的东西来使用像Treetop这样的工具。我的语法分析器在GitHub上,以防有人希望帮助我改进它。class{initialize=lambda(name){receiver.name=name}greet=lambda{IO.puts("He

  6. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  7. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  8. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  9. ruby - 如何使用 RSpec::Core::RakeTask 创建 RSpec Rake 任务? - 2

    如何使用RSpec::Core::RakeTask初始化RSpecRake任务?require'rspec/core/rake_task'RSpec::Core::RakeTask.newdo|t|#whatdoIputinhere?endInitialize函数记录在http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/RakeTask#initialize-instance_method没有很好的记录;它只是说:-(RakeTask)initialize(*args,&task_block)AnewinstanceofRake

  10. ruby - 为什么 SecureRandom.uuid 创建一个唯一的字符串? - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?

随机推荐