简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM