Ernest Melville
Ernest Melville

Reputation: 65

Can't call global class from namespaced class in PHP. Using Composer's autoload

I'm using composer to create an autoload file, and all that jazz works as expected.

The problem is: when I try to call a globally defined class, it keeps looking inside the namespace, instead of the global scope. Even though I use the \ escape as in "new \WC_Order();"

I've configured composer.json to autoload MyNamespace in the correct dir and include 'vendor/autoload.php' in my wordpress theme's function.php, and create a new instance, which works. Everything about this process works.

include 'vendor\autoload.php';
$myclass = new MyNamespace\MyClass()

Here's where the error occurs in the file 'MyNamespace\MyClass.php:

namespace MyNamespace;

class MyClass {

    public function __construct()
    {
        $order = new \WC_Order(1234);
    }

}

PHP throws a fatal error:

Fatal error: Uncaught Error: Class 'MyNamespace\WC_Order' not found in ...\MyNamespace\MyClass.php

Any tips or hints would be greatly appreciated!

Edit: My composer/directory setup

composer.json

{
    "autoload": {
        "psr-4": {
            "MyNamespace\\": "MyNamespace"
        }
    },
    "require": {
        "guzzlehttp/guzzle": "^6.3"
    }
}

functions.php is in the root and the class is in MyNamespace/MyClass.php

Upvotes: 0

Views: 435

Answers (2)

Ernest Melville
Ernest Melville

Reputation: 65

I figured it out. Since this is Wordpress, I should have hooked into an action. Woocommerce hadn't been loaded yet. As soon as I used add_action('init', 'doMyStuff'); it worked.

I still find it strange that the message was that it couldn't find the class inside the namespace though.

Upvotes: 1

Web-Fu
Web-Fu

Reputation: 85

Try:

include 'vendor\autoload.php';
$myclass = new \MyNamespace\MyClass();

Or:

include 'vendor\autoload.php';

use MyNamespace\MyClass;

$myclass = new MyClass();

You can find a guide here: https://www.php.net/manual/en/language.namespaces.importing.php

Upvotes: 0

Related Questions