1

Here is a simple example:

class Class_A {   
    protected $_property;

    public function method()
    {
        Class_B::method($this);
    }

    public function getProperty()
    {
        return $this->_property;
    }
}

class Class_B {
    public static function method(Class_A $classA)
    {
        $classA->getProperty();
    }
}

$classA = new ClassA();
$classA->method();

Is it ever okay to pass $this as a parameter to the method of another class? Or is that always going to be tight coupling? I could pose another similar example using a Factory Pattern in place of the static method call.

Dan
  • 1,559
  • 1
  • 15
  • 18

2 Answers2

1

It depends on the exact behaviour of Class_A and Class_B, but in general it would probably be better to define an interface which is implemented by Class_A and type hint for that. The methods of Class_A that are required by Class_B (e.g. getProperty()) should appear in your interface. Then, if you want to switch Class_A with another class at a later date, all it has to do is implement the same interface.

cmbuckley
  • 40,217
  • 9
  • 77
  • 91
  • Thanks that makes a lot of sense. Now I'm trying to think of the exact behaviour that would make it tightly coupled – Dan Dec 18 '11 at 22:12
  • See [this question](http://stackoverflow.com/questions/2832017/what-is-the-difference-between-loose-coupling-and-tight-coupling-in-object-orien) for more information. In summary: it's the fact that in your example `Class_B` is dependent on `Class_A`, whereas using an interface removes that dependency. You could independently test `Class_B` by using a mock object that implemented that interface. – cmbuckley Dec 18 '11 at 22:36
0

Yet again, it depends on the behavior of the classes in question, but if there was another Class_C for example that also used Class_B 's static method you might want to consider having Class_A and Class_C extend Class_B. More information can be found on the php object inheritance page.