WooCommerce OrderUtil Class Does Not Exist Despite Being Imported

148 Views Asked by At

Working with troubleshooting an issue on a Wordpress/WooCommerce site.

There is a plugin that uses the WooCommerce OrderUtil class and imports it before a handler class is declared.

use Automattic\WooCommerce\Utilities\OrderUtil;

class Order_Handler {

    public function set_checkout_order_meta() {

        if ( class_exists('OrderUtil') ) {

            // do some things here

        }

    }

}

For a reason that I cannot figure out, class_exists('OrderUtil') returns false.

However class_exists('Automattic\WooCommerce\Utilities\OrderUtil') returns true.

I am stuck on how an imported class that exists is not available in Order_Handler.

Note: I cannot update the code that checks for the OrderUtil class without breaking the plugin upgrade path.

1

There are 1 best solutions below

0
SecureIT On BEST ANSWER

Sharing the answer found in a user-contributed note in the class_exists() docs on php.net

If you are using aliasing to import namespaced classes, take care that class_exists will not work using the short, aliased class name - apparently whenever a class name is used as string, only the full-namespace version can be used

use a\namespaced\classname as coolclass;

class_exists( 'coolclass' ) => false

Solution is to use either of the following to check if the class exists

class_exists('Automattic\WooCommerce\Utilities\OrderUtil')

or

class_exists( OrderUtil::class)