Jump to content

How to communicate back and forwards between classes?


UrbanDweller

Recommended Posts

Ive always had a bit of trouble with php and effectively talking between classes,  as the example below shows I want to call a first class->function that will later call a different class and its function then call the previous class again. I havent been able to find any examples that state how to do this if possible.

 

<?php
class A{
function b(){
	//does required code etc...
	$B = new B();
	$B->BA():
}

function AB(){
	echo "I WANT TO END UP HERE, from class B function BA";	
}
}

class B{
function BA(){
	//does required code etc...
	//		
	//Unsure how to call class/function A->AB
}

}

$a = new A();
$a->AB();
?>

 

Is this possible as it helps separate my code in to nice and easy to read

 

Thanks

Why is it going from A to B and back to A again? Seems weird.

 

Pass A to B's method.

$B = new B();
$B->BA($this);

function BA(A $a) {
    $a->AB();
}

 

Yeah it is but how I started coding this, I may have to reconsider moving some functions out of class a into class b instead as the variable pass through will get messier than i want it.

What you're looking for is an Observer Pattern or Closures, in order to implement callbacks in an agnostic manner in a class.

 

Observer: class A should maintain a list of observers (B can register with A), and update them on Event.

Closure:  you can use anonymous functions / closures to bind a callback to B from A (requires PHP 5.3).

 

Here's an example of anonymous functions used in PHP for callbacks (you need to specify a context because binding isn't avail in PHP yet):

 

<?php

class A {
    private $callback;
    private $callbackContext;
    public function __construct($callback=null, $callbackContext=null) {
        $this->callback = $callback;
        $this->callbackContext = $callbackContext;
    }
    public function foo() {
        echo "A just fooed!<br />\n";
        if ($this->callback instanceof Closure) {
            $callback =& $this->callback;
            $callback($this->callbackContext);
        }
    }
}

class B {
    private $a;
    public function __construct() {
        $this->a = new A(function($self) {
            $self->bar();
        }, $this);
    }
    public function foo() {
        echo "B just fooed!<br />\n";
        $this->a->foo();
    }
    public function bar() {
        echo "B just barred!<br />\n";
    }
}

$b = new B();
$b->foo();

?>

Why is it going from A to B and back to A again? Seems weird

 

I decided to re-look over my code and have completely reworked it into a cleaner look without having to back in to previous classes. Thanks for comment :P

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.