Question

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.

Was it helpful?

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top