March 30, 2012
How to create a "listening(waiting?)" method
Question by Andrius Naruševičius
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 🙂
Answer by Starx
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();
}
}