开发者

Resolve php endless recursion issue

I'm currently running into an endless recursion situation.

I'm implementing a message service that calls various object methods.. it's quite similar to observer pattern..

Here's whats going on:

Dispatcher.php

class Dispatcher {
...
    public function message($name, $method) {

    // Find the object based on the name
    $object = $this->findObjectByName($name);

    if(!$object->decorations))
            // Decorate the object
        $object = new $name($object); // This is where it locks up.
            $object->decorations = true;
    }

    return $object->$method();
...
}

class A {
    function __construct()
    {
        $Dispatcher->message("B", "getName");
    }

    public function getName() {
        return "Class A";
    }

}

class B {
    function __construct()
    {
            // Assume $Dispatcher is the classes
        $Dispatcher->message("A", "getName");
    }

    public function getName() {
        return "Class B";
    }

}

It locks up when neither object is initialized. It just goes back and forth from message each other and no one can be initialized.

I'm looking for some kind of queue implementation that will make messages wait for each other.. One where the return values still get set. I'm looking to have as little boilerplate code in class A and class B as possible.


I'm getting a lot of talk about the not_initialized method, unfortunately I feel that the discussion is going in the wrong direction. That's my fault, I'll explain the situation a little more (and b开发者_JAVA百科etter I hope).

$object implements a decorator pattern - that is $object gets more features (methods) when I initialize class A and class B. I need to use those features made available from the decorations in the messaging method, that's why if its not yet decorated, decorate it. I really do not think not_initialized would have been the issue because when say $objectA is checked it is not yet decorated - So I want to add those methods to it. Class A and B are decorator classes. So not_initialized is correct at the time. It gets stuck when I try to decorate the object. I changed the code to better reflect this situation.


This is not an example of deadlock, but of endless recursion. Most likely your not_initialized function returns true until the constructor has been fully run. As a result, constructing an object of type A will indirectly call the B constructor, which will call the A constructor, ad infinitum.

You will have to change the not_initialized function, or move the message dispatching out of the constructors if you can.

Deadlock is a situation that involves multiple processes. In this case, there is only a single process.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜