-1

Here is my problem, when I defined a class name with "use" in php and then I tried to include a file, it loses the "used name" that I defined in the parent file. Like this:

File1.php:

use \cdb\Date as H;
echo "<br> > 1 > " . H::Now();
require 'File2.php';

File2.php:

echo "<br> > 3 > " . H::Now();

When I execute my File1.php code this error appears:

Fatal error: Class 'H' not found in File2.php on line 3

  • 3
    Possible duplicate of [How does the keyword "use" work in PHP and can I import classes with it?](https://stackoverflow.com/questions/10965454/how-does-the-keyword-use-work-in-php-and-can-i-import-classes-with-it) –  Sep 18 '18 at 18:34

1 Answers1

1

Scoping rules for importing

Importing rules are per file basis, meaning included files will NOT inherit the parent file's importing rules.

You need to add the use statement in the File2.php too.

update:

If an included file are in the same namespace (\cdb) then you don't need to import \cdb\Date.

In other cases, you can use class_alias() to create an another name for the class in runtime , BUT it is a bit tricky and better to use a regular explicit import.

Timurib
  • 2,735
  • 16
  • 29
  • Thank's for the clarification man, theres a way to do that ? Instead of calling "\cdb\Date" only use "Date" in my included files – bCerquiare Jan 03 '17 at 18:06