[英]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();"
即使我像在“ 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. 我已经将composer.json配置为将MyNamespace自动加载到正确的目录中,并在我的wordpress主题的function.php中包含“ vendor / autoload.php”,并创建一个有效的新实例。 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: 这是文件'MyNamespace \\ MyClass.php中发生错误的位置:
namespace MyNamespace;
class MyClass {
public function __construct()
{
$order = new \WC_Order(1234);
}
}
PHP throws a fatal error: PHP引发致命错误:
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 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 functions.php在根目录中,而类在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 您可以在此处找到指南: https : //www.php.net/manual/zh/language.namespaces.importing.php
I figured it out. 我想到了。 Since this is Wordpress, I should have hooked into an action.
既然这是Wordpress,我应该迷上一个动作。 Woocommerce hadn't been loaded yet.
Woocommerce尚未加载。 As soon as I used add_action('init', 'doMyStuff');
一旦我使用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. 我仍然感到奇怪的是,消息是它虽然无法在命名空间中找到该类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.