Reputation: 1302
I have a script A, placed in namespace A. In this script, I wrapped all of the functions defined inside it in a class A.
Then I have another script B, placed in namespace B, also with all of the functions of the script wrapped into a class B.
The class B contains 10 functions, whereas only one function B_1 of them needs access to a function defined in class A. Hence, I decided to place the require script_A
statement inside that function B_1.
Problem is: I want to use a function A_1 of class A in namespace A inside that function B_1 of class B, defined in namespace B. When I do this inside function B_1:
require "script_A.php";
use namespace_A\class_A;
My syntax corrector tells me unexpected use of "use"
. The only way my require script_A
inside function B_1 with subsequential use of function A_1 seems to be possible is by invoking A_1 using a fully qualified namespace:
require "script_A.php";
\namespace_A\class_A::A_1();
I just wanted to double-check if that's usual? Is it really not possible to use "use" to import namespaces inside PHP functions of other namespaces ? Or am I misunderstanding sth? Full code example of script B:
namespace B;
class B {
public static function B1() {
require_once "script_A.php";
use A\classA;
}
}
My linter reports an error on the use
here. My alternative was the code below, which works:
namespace B;
class B {
public static function B1() {
require_once "script_A.php";
\A\classA::A1();
}
}
Upvotes: 0
Views: 86
Reputation: 4534
From the PHP manual:
Scoping rules for importing
The use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations. This is because the importing is done at compile time and not runtime, so it cannot be block scoped.
The following example will show an illegal use of the use keyword:
<?php
namespace Languages;
function toGreenlandic()
{
use Languages\Danish; // <-- this is wrong!!!
// ...
}
?>
This is where use
should be put - in the global space:
<?php
namespace Languages;
use Languages\Danish; // <-- this is correct!
function toGreenlandic()
{
// ...
}
?>
Upvotes: 1