rhlee
rhlee

Reputation: 4046

How do I override a php method in situ

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.

Upvotes: 2

Views: 1593

Answers (3)

Alex Pliutau
Alex Pliutau

Reputation: 21957

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();
   }   
}

Upvotes: -1

Dave
Dave

Reputation: 506

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';
    }
}

Upvotes: 2

Explosion Pills
Explosion Pills

Reputation: 191749

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.

Upvotes: 2

Related Questions