Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to replace a function within a PHP class?

This is actually comes from a specific WordPress issue but there's a more general PHP point behind it which I'm interested to know the answer to.

The WordPress class is along these lines:

class Tribe_Image_Widget extends WP_Widget {
    function example_function(){
        // do something useful
    }
}

Is there any way in PHP that I can replace example_function() from outside the class?

The reason I want to do this is that the class is from someone else's WP plugin (and has several functions in the class) and I want to continue receiving updates to the plugin but I want one of the functions adapted. If I change the plugin, then I'll lose all my own changes each time. SO if I have my own plugin which just changes that one function, I avoid the problem.

like image 825
user114671 Avatar asked Jan 10 '12 16:01

user114671


3 Answers

It sounds like what you want to do is extend the class, and override that particular function.

Class Your_Tribe_Image_Widget extends Tribe_Image_Widget
{
   function example_function() {
     // Call the base class functionality
     // If necessary...
     parent::example_function();

     // Do something else useful
   }
}
like image 111
Michael Berkowski Avatar answered Nov 08 '22 07:11

Michael Berkowski


You could probably have an include_once to the target plugin at the top of your file and then extend the class of the target plugin instead of the WP_Widget class:

include_once otherPlugin.php
class My_Awesome_Plugin_Overloaded extends Someone_Elses_Awesome_Plugin{
    function example_function(){
         return 'woot';
    }
}
like image 1
Paul Bain Avatar answered Nov 08 '22 07:11

Paul Bain


As long as the method in the existing class hasn't been marked as final, you can just subclass and override it

class My_Tribe_Image_Widget extends Tribe_Image_Widget {
    //override this method
    function example_function(){
        // do something useful
    }
}
like image 1
meouw Avatar answered Nov 08 '22 05:11

meouw