Search code examples
phploose-coupling

Is passing $this to a static method tight coupling?


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.


Solution

  • 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.