user2650277 user2650277 - 13 days ago 6
PHP Question

Using a method in multiple classes

I have a specific method that is used in multiple classes.The problem here is that if i want to do changes in the method , I need to replicate that in other classes as well.How can i fix this ?

Answer

The answer is "it depends". And in this case it depends on the purpose of the method, the design of your application, and such like.

One approach is - as Mahfuzel points out - is to use a trait:

<?php

class MyClass {
    use MyTrait;
}


trait MyTrait {

    public function greeter($name){
        echo "Hello $name";
    }
}


$myObj = new MyClass();
$myObj->greeter("user2650277"); // Hello user2650277

This basically does a "dumb" import of the trait's code into your class. I'd use this as kinda of an "interface implementation" in a class: a trait defines a specific additional behaviour your class needs. If your method can be considered like that, then traits are easy.

If your method is just a helper function, then perhaps stick it in its own class, and make it static:

<?php

class MyClass {

    public function myMethod($name){
        MyOtherClass::greeter($name);
    }

}

class MyOtherClass {

    public static function greeter($name){
        echo "Hello $name";
    }
}

$myObj = new MyClass();
$myObj->myMethod("user2650277"); // Hello user2650277

Or perhaps your method has state of its own, and should simply be a method of that class, not a static function:

<?php

class MyClass {

    public function myMethod($name){
        $otherClass = new MyOtherClass($name);
        $otherClass->greeter();
    }

}

class MyOtherClass {

    private $name;

    public function __construct($name){
        $this->name = $name;
    }

    public function greeter(){
        echo "Hello {$this->name}";
    }
}

$myObj = new MyClass();
$myObj->myMethod("user2650277"); // Hello user2650277

(obviously you might want to use dependency injection rather than just creating that instance of MyOtherClass directly in the code of MyClass, but that's kinda outwith the scope of your question).

I have purposely not included another option here: creating a base class, hoisting the method up into that, and making MyClass (and your other classes that need the function) extend that. That's almost certainly going to be the wrong approach, as it's unlikely the inheritance hierarchy will fulfil the "MyClass IS A MyBaseClass" which it must do if you're using inheritance. MyClass does not simply become a subclass of another in a design sense simply because it wants to use a method of the potential base class. That's poor OO. In general stick to the addage "favour composition over inheritance", which all the options above do.

Don't simply pick the easiest solution to type in... think about the architecture of your app, and implement the appropriate solution.

Let me know if you need anything clarified.

Comments