Search code examples
phpwordpressclassoverridingmonkeypatching

PHP: Override a plugin class method


I'm currently using a plugin that allows to make a custom checkout process, cartflows-pro. I need to add some details in the checkout and override a class method.

I tried to override the class method but the extended child class is never called.

Action called in my plugin

add_action( 'cartflows_pro_init', function() {

    if ( class_exists( 'Cartflows_Pro_Variation_Product' ) )
    {
        class Cartflows_Pro_Variation_Product_overriden extends Cartflows_Pro_Variation_Product {

            public function single_sel_variation_product_markup( $current_product, $single_variation, $type = '' ) {
                               // some custom code
                return $output;
            }

        }

        Cartflows_Pro_Variation_Product::get_instance();

    } 
} );

The plugin to override :

class Cartflows_Pro_Variation_Product {
    private static $instance;

    public static function get_instance() {
        if ( ! isset( self::$instance ) ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function __construct() {

        add_action( 'cartflows_add_before_main_section', array( $this, 'product_variation_option_position' ) );

    }

    function product_variation_option_position( $output ) {
                // some code
        $output .= $this->single_sel_variation_product_markup( $current_product, $single_variation );
                return $output;
        }

    function single_sel_variation_product_markup( $current_product, $single_variation, $type = '' ) {
                // some code
                return $output;
            }


}

Cartflows_Pro_Variation_Product::get_instance();

The parent class file is called in an other class

    function include_required_class() {
        include_once CARTFLOWS_PRO_CHECKOUT_DIR . 'classes/class-cartflows-pro-variation-product.php';
    }

How can I override the method ? If I extend the class before it's loaded it throws an error, so I have to call in on the 'cartflows_pro_init' hook.

If I call new Cartflows_Pro_Variation_Product_overriden(); It's working but I get the output code displayed twice 1 with the normal code (parent) and 1 with the custom code (child)

If I call new Cartflows_Pro_Variation_Product(); I get the basic output code displayed twice 2 output without the custom code

If I call Cartflows_Pro_Variation_Product::get_instance(); It does nothing

Any idea of how I should override the method ? I don't really know how to autoload.


Solution

  • Just to update this question.

    I didn't succeed to override the method so I tried to do it another way

    I solved it by adding the data that I needed with ajax and directly output it !