开发者

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 w开发者_如何学Pythonould extend if I could, but I cant.


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


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜