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

This actually comes from a specific WordPress issue, but there is a more general PHP point for which I am interested to know the answer.

The WordPress class corresponds to the following 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()outside the class?

The reason I want to do this is because the class belongs to another WP plugin (and has several functions in the class), and I want to keep getting plugin updates, but I want one of the functions to be adapted. If I change the plugin, I will lose all my own changes every time. SO, if I have my own plugin that just changes one function, I avoid the problem.

+5
source share
3

, extend .

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
   }
}
+9

, include_once , WP_Widget:

include_once otherPlugin.php
class My_Awesome_Plugin_Overloaded extends Someone_Elses_Awesome_Plugin{
    function example_function(){
         return 'woot';
    }
}
+1

Until the method in the existing class has been marked as final, you can simply subclass and override it

class My_Tribe_Image_Widget extends Tribe_Image_Widget {
    //override this method
    function example_function(){
        // do something useful
    }
}
+1
source

All Articles