如何从名称space 的文件中向全局space 声明一个新的class?

How to declare a new class to the global space from within a namespace'd file?

或者完全简洁地回答我的问题:

(在 Namespace 的文件中) 是否可以声明一个新的 class ( 扩展 class定义在全局名space)到全局space?

例如

namespace Roots\Sage\VisualComposer;
...

...
if ( class_exists( '\WPBakeryShortCodesContainer' ) ) {
    class WPBakeryShortCode_Your_Gallery extends \WPBakeryShortCodesContainer {}
}

一些调试信息

echo 'x: ' . WPBakeryShortCodesContainer::class . PHP_EOL;

echo 'y: ' . WPBakeryShortCode_Your_Gallery::class . PHP_EOL;

Returns:

x: WPBakeryShortCodesContainer

y: Roots\Sage\VisualComposer\WPBakeryShortCode_Your_Gallery

所以我 WPBakeryShortCode_Your_Gallery 的新 class 在 Roots\Sage\VisualComposer 名称space 中,而不是全局...

对命名空间使用替代语法:

namespace Roots\Sage\VisualComposer {
  //...    
}
//...
namespace Roots\Sage\VisualEditor {
  //...    
}
//...
namespace {  // global code
  if ( class_exists( '\WPBakeryShortCodesContainer' ) ) {
    class WPBakeryShortCode_Your_Gallery extends \WPBakeryShortCodesContainer {}
  }
}

更多:Defining multiple namespaces in the same file