FLOQ Design
FLOQ Design

Reputation: 117

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

or to be completely concise with my question:

( Within a Namespace'd file ) is it possible to declare a new class ( that extends a class defined in the global namespace ) to the global space?

For example

namespace Roots\Sage\VisualComposer;
...

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

Some debug info

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

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

Returns:

x: WPBakeryShortCodesContainer

y: Roots\Sage\VisualComposer\WPBakeryShortCode_Your_Gallery

So my new class of WPBakeryShortCode_Your_Gallery is in the Roots\Sage\VisualComposer namespace, not the global...

Upvotes: 2

Views: 296

Answers (1)

Gennadiy Litvinyuk
Gennadiy Litvinyuk

Reputation: 1595

Use alternative syntax for namespaces:

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

More: Defining multiple namespaces in the same file

Upvotes: 2

Related Questions