Search code examples
phppythonoopclosuresanonymous-methods

PHP Import Foreign Class' Method into MyClass


Wondering if this is possible in PHP Land:

Let's say I have a class as follows:

class myClass{
  var $myVar;
    ...
  myMethod(){
      $this->myVar = 10;
  }
}

and another class:

class anotherClass {
   ...
   addFive(){
       $this->myVar += 5;
   }
}

The 'anotherClass' is 3500 lines long and I just want the single 'addFive' method to use in myClass.

  • Is there a way I can import the function and be able to call it in my class and the $this would reference the myClass object?
  • Is this good/bad practice?
  • (optional) How does this work in Python? (Just curious as I'm starting to learn Python)

Solution

  • The easiest way to do this is have one class extend the other

    class myClass extends anotherClass {
    }
    

    The myClass class now has access to all the methods of anotherClass that are public or protected.

    If you only want the class to have one method of the other, or it's not practical to have one class extends from the other, there's nothing built into PHP that will allow you to do this. The concept you're looking to Google for is "Mixin", as in Mix In one class's functionality with another. There's an article or two on some patterns you could try to achieve this functionality in PHP, but I've never tried it myself.

    Good idea/Bad Idea? Once you have the technique down it's convenient and useful, but costs you in performance and makes it harder for a newcomer to grok what you're doing with your code, especially (but not limited to) someone less familiar with OO concepts.