D
D
Dubrovin2018-04-24 12:23:57
PHP
Dubrovin, 2018-04-24 12:23:57

How to create a global class inside namespace?

Namespace ABC is declared at the beginning of the file, how can a class be created in the global namespace?

namespace ABC;
//этот класс должен быть внутри ABC
class A {
}
//а этот класс должен быть глобальным
class B {
}

The class declaration is somewhere in the middle of the code (nested inside methods and conditions), so using namespace {} does not work.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Melkij, 2018-04-24
@Dubrovin

Follow the PSR and move the class declaration to a separate file in the expected PSR-4 (or PSR-0) path.

Z
Zhainar, 2018-04-24
@zhainar

But if you suddenly want

namespace ABC {
//этот класс должен быть внутри ABC
  class A {
    public static function nspc()
    {
      return __NAMESPACE__;
    }
  }
  
}

namespace {
  //а этот класс должен быть глобальным
  class B {
    public static function nspc()
    {
      return __NAMESPACE__;
    }
  }
  
  class C extends ABC\A {
  }
  
  echo ABC\A::nspc();
  echo '<br>----------------<br>';
  echo B::nspc();
  echo '<br>----------------<br>';
  echo C::nspc();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question