4

I have a file called "init.php" where I include all my classes with a namespace. One of this will be for example : MyClass\Helper.

Always in the init, after those classes, there's an inclusion of another file ( b.php ) that uses MyClass\Helper.

Finally, this file "init" is required by the index that also uses MyClass\Helper.

So:

init.php
  -> Require libs/Helper.php ( final namespace: MyClass\Helper )
  -> Require b.php
       -> Use MyClass\Helper

index.php
  -> Require init.php
  -> Use MyClass\Helper

Now I want to put in my init.php, after the inclusion of all classes use MyClass\Helper as Helper but it doesn't work ( class not found in the other files if I use "Helper" instead of MyClass\Helper ) and I have to put it manually in b.php ( included after the classes ) and in the index.php.

There is a way to "save" the "use as" for all files?

Theraloss
  • 700
  • 2
  • 7
  • 30
  • 1
    Sounds impossible by using only namespaces features (in particular the keyword `use`), according to the PHP manual http://php.net/manual/en/language.namespaces.importing.php > Importing rules are per file basis, meaning included files will NOT inherit the parent file's importing rules. – Maxime Pacary Apr 14 '16 at 22:18
  • 1
    You may be interested by this answer: http://stackoverflow.com/a/19890311/488666 – Maxime Pacary Apr 14 '16 at 22:26
  • Frosty Z, your comment is correct. Please consider re-doing it as an answer so everyone can upvote it. Namespaces are handled on a file-by-file basis in PHP and many other languages. – Dave Ross Apr 14 '16 at 23:00
  • Frosty Z thanks, but creating another class to mask the real one, the logic of "using namespace to avoid the problem of classes with same name" does not make sense anymore, or am I wrong? Maybe it's the same with "use as", idk ahah. By the way thanks, if you create an answer I can check as correct. – Theraloss Apr 15 '16 at 07:04

1 Answers1

0

The whole idea is to try not to include anything. Try to use spl_autoload_register to register your classes autoloader so you don't need to use 'include' and 'require'

Amorphous
  • 779
  • 7
  • 27