views:

148

answers:

3

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)
A: 

If your myClass extends anotherClass it inherits all the methods and properties of anotherClass (except those marked private).

class AnotherClass {
  protected $myVar;
  public function addFive(){
    $this->myVar += 5;
  }
}

class MyClass extends AnotherClass {
  public function __construct() {
    $this->myVar = 0;
  }

  public function myMethod(){
    $this->myVar = 10;
  }
}

$m = new MyClass;
$m->myMethod();
$m->addFive();
var_dump($m);

prints

object(MyClass)#1 (1) {
  ["myVar":protected]=>
  int(15)
}
VolkerK
Thanks. Yes, but I want to avoid extending the 3500 line class as it has 3490 lines of functionality I don't need. Basically, I'm looking to extend only that one method.
safoo
+2  A: 

A better approach would be to move the complex method into its own class. Then both of your classes can instantiate it, pass any necessary data, and call the method.

JW
+2  A: 

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.

Alan Storm
The link shows exactly what I wanted to do. Reading up more on it. Thanks.
safoo
This might work, yet the use of eval to accomplish even a justifiable end like this makes me leery.
The Wicked Flea