php – How to override WordPress Plugin class method

exception or error:

I have a plugin which class is something like that:

<?php

namespace myPro\EventCalendarPro;

use WP_Widget;

/**
 * Adds ECP_Widget widget.
 */

class ECP_Widget extends WP_Widget {

    public function widget () {

    }
}

?>

Now, how can I override the widget method from my theme functions.php file?

How to solve:

The simple answer to this question is “You cannot do this”.

Because in PHP you cannot redefine classes, methods, and functions. But you can use PHP Runkit extension to redefine your methods

Runkit function to redefine method is runkit_method_redefine

Code Example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// create an Example object
$e = new Example();

// output Example::foo() (before redefine)
echo "Before: " . $e->foo();

// Redefine the 'foo' method
runkit_method_redefine(
    'Example',
    'foo',
    '',
    'return "bar!\n";',
    RUNKIT_ACC_PUBLIC
);

// output Example::foo() (after redefine)
echo "After: " . $e->foo();
?>

But for first you should install the php-runkit extension on your server.

How to install Runkit

Leave a Reply

Your email address will not be published. Required fields are marked *