views:

55

answers:

3

How do I override a class method in php in situ, i.e. without extending it?

I would extend if I could, but I cant.

+1  A: 

You mean overload the method? You can't. PHP does not support overloading. You either have to create a new method in the same class or override it in a child class.

..or that would be the case except for the __call() and __callStatic() methods. These allow you to pass the method name and arguments as parameters. You can check the method name and the arguments to simulate overloading. If the arguments are different but the method name is the same, do a different thing than normal.

tandu
+3  A: 

May have already been answered in this question here. Short answer, you can do it with PHP's runkit, but it looks horribly out of date (ie hasn't been touched since 2006) and may no longer work.

Your best bet may be to rename the original class and then extend it with a new class with the original name. That is

class bad_class { 
    public function some_function {
        return 'bad_value';
    }
}

becomes

class old_bad_class { 
    public function some_function {
        return 'bad value';
    }
}        

class bad_class extends old_bad_class { 
    public function some_function {
        return 'good value';
    }
}
Dave
A: 

Without extending you can call method from one class in other. But it is a bad practice.

class First
{
   public function doIt()
   {
      echo 'Done';
   }
}

class Second
{
   public function doIt()
   {
      $first = new First;
      $first->doIt();
   }   
}
Alexander.Plutov
In what situation would you be able to create and use a new class conditionally but NOT extend another class?
tandu