How plugins_loaded works?

I am developing a plugin for woocommerce payment gateway.

When I put the code of class definition inside the callback function who is fired by 'plugins_loaded',it works.

?php
    add_action('plugins_loaded','WC_test_gateway_plugin');
    function WC_test_gateway_plugin{
        class my_gateway extends WC_Payment_Gateways{
            //code
        }
    }
?

But when I put it into global scope, it will show that the WC_Payment_Gateways is undefined.

?php
    class my_gateway extends WC_Payment_Gateways{
        //code
    }
?

What's the difference between these 2 practices?

Is it a bad practice to put class definition inside callback function? Any better way for it?

Topic woocommerce-offtopic plugin-development Wordpress

Category Web


Use your class definition in a separate file, say in /your-plugin-dir/classes/my-gateway.php like usual:

    <?php
        class my_gateway extends WC_Payment_Gateways {
            //code
        }
    ?>

Then use this CODE to include the file on plugins_loaded action from your main plugin file:

    add_action('plugins_loaded', 'WC_test_gateway_plugin');
    function WC_test_gateway_plugin() {
        require_once plugin_dir_path( __FILE__ ) . 'classes/my-gateway.php';
        // instantiate your class here or in your class file or anywhere after this function is called.
    }

Now you'll get access to WC_Payment_Gateways because by now WC_Payment_Gateways is defined, since WordPress fires plugin_loaded action hook only after all the plugins have loaded their main files.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.