如何创建“监听(等待?)”方法

Lets say I have:

class X
{
    function a()
    {
        echo "Hello, ";
    }
    function b()
    {
        echo "John!";
    }
}

and then

Y = new X();
Y->a();

but once the method a is called, I also want the method b called immediately after it (so it kind of listens(waits?) till the moment when a is called and finished), so the output is

Hello, John

Is it possible to do that, and how that should look? And no, calling $this->b(); at the end of method a is NOT a solution to what I want to do :) Thanks in advance :)

You are searching for observer pattern. Read some example from the internet, you should be able to do what you are attempting.

However, A very simple example of using observer pattern:

class X
{
    private $observer;
    public function __construct() {
        $this -> observer = new XObserver();
    }

    function a() {
        echo "Hello,";      
        $this -> observer -> aExecuted($this);
    }

    function b() {
        echo "John!";
    }
}

class XObserver {

    public function aExecuted($obj) {
        return $obj -> b(); 
    }
}

Can you elaborate more on what you're trying to do? Because observer pattern suggested it involves attaching a list of external objects and implementing some kind of event-based system. And i am not sure that the observer approach fits your needs from what you describe.

There is basicly no possibility to call another method once a method has finished running, and i don't see the need for it. A semi correct approach could be to use __call and make the a() method protected/private, and in the __call intercept the call, run method a() and immediately run method b().

Unfortunatelly without much details i cannot provide or think of a better way to solve this problem. There are no php magic methods for this purpose.