Why does not a single file work, I just can not understand?

<?php namespace Lev{ const MyConst = 'MyValue'; } namespace Lev\MyClasses{ class MyClass{ public $a = 1; public function MyMethod(){ echo 'Hello'; } } } class MyClass{ public $a = 5; } $a = new Lev\MyClasses\MyClass(); $b = new MyClass(); echo $a->a; echo $b->a; 

/////////////////////////////////

 <?php namespace PHP7\functions; header('Content-Type: text/html; charset=utf-8'); function debug($obj){ echo '<pre>'; var_dump($obj); echo '</pre>'; echo $obj->getTitle(); } namespace PHP7\classes; class Page{ protected $title; protected $content; public function __construct($title = '', $content = ''){ $this->title = $title; $this->content = $content; } function getTitle(){ return $this->title; } } $page = new PHP7\classes\Page('ΠšΠΎΠ½Ρ‚Π°ΠΊΡ‚Ρ‹', 'Π‘ΠΎΠ΄Π΅Ρ€ΠΆΠΈΠΌΠΎΠ΅ страницы'); PHP7\functions\debug($page); 

    1 answer 1

    In php fairly informative error messages.

    Fatal error: No code may exist outside of namespace {in / in / in NMepG on line 16

    Part of the code in the first file is out of any namespace.
    You must specify it, at least anonymous.

     <?php namespace Lev{ const MyConst = 'MyValue'; } namespace Lev\MyClasses{ class MyClass{ public $a = 1; public function MyMethod(){ echo 'Hello'; } } } namespace { class MyClass{ public $a = 5; } $a = new Lev\MyClasses\MyClass(); $b = new MyClass(); echo $a->a; // 1 echo $b->a; // 5 } 

    Fatal error: Uncaught Error: Class 'PHP7 \ classes \ PHP7 \ classes \ Page' not found

    It is immediately clear that a similar indication of the class name is interpreted relative to the current namespace.
    You can, for example, add the first slash to make a start from the root:

     $page = new \PHP7\classes\Page('ΠšΠΎΠ½Ρ‚Π°ΠΊΡ‚Ρ‹', 'Π‘ΠΎΠ΄Π΅Ρ€ΠΆΠΈΠΌΠΎΠ΅ страницы'); \PHP7\functions\debug($page); 
    • Thanks, but I don’t understand why the creation of the class and its output should be put inside the namespace? - DivMan
    • This is the syntax of namespaces. In general, it is advisable not to mix class declarations and client executable code in a single file. php.net/manual/ru/language.namespaces.definitionmultiple.php - vp_arth
    • This syntax was designed solely for the ability to merge many files into one for optimization, before deploying. When developing it is desirable to adhere to PSR-0/4 compatible agreements ... - vp_arth
    • that is, without the first slash, will it search outside the file? - DivMan
    • Outside the file, it will only search if the autoloader is initialized. Without a slash, it will look for the class \Π’Π΅ΠΊΡƒΡ‰ΠΈΠΉ\нСймспСйс\Π£ΠΊΠ°Π·Π°Π½Π½Ρ‹ΠΉ\нСймспСйс\Класс , as seen in the error message. - vp_arth