在命名空间 B 的函数中使用命名空间 A 的函数
Use function of namespace A in function of namespace B
我有一个脚本 A,放在命名空间 A 中。在这个脚本中,我将其中定义的所有函数包装在 class A 中。
然后我有另一个脚本 B,放在命名空间 B 中,也将脚本的所有功能包装到 class B.
class B 包含 10 个函数,而其中只有一个函数 B_1 需要访问 class A 中定义的函数。因此,我决定将 require script_A
函数内的语句 B_1.
问题是:我想在名称空间 B 中定义的 class B 的函数 B_1 中使用名称空间 A 中 class A 的函数 A_1。当我在函数 B_1:
中执行此操作时
require "script_A.php";
use namespace_A\class_A;
我的语法校正器告诉我 unexpected use of "use"
。我的 require script_A
内部函数 B_1 以及随后使用函数 A_1 的唯一方法似乎是通过使用完全限定的命名空间调用 A_1:
require "script_A.php";
\namespace_A\class_A::A_1();
我只是想仔细检查一下这是否正常?真的不可能使用“使用”在其他名称空间的 PHP 函数中导入名称空间吗?还是我误解了某事?脚本 B 的完整代码示例:
namespace B;
class B {
public static function B1() {
require_once "script_A.php";
use A\classA;
}
}
我的 linter 在 use
此处报告错误。我的替代方案是下面的代码,它有效:
namespace B;
class B {
public static function B1() {
require_once "script_A.php";
\A\classA::A1();
}
}
来自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.
以下示例将显示对 use 关键字的非法使用:
<?php
namespace Languages;
function toGreenlandic()
{
use Languages\Danish; // <-- this is wrong!!!
// ...
}
?>
这是应该放置 use
的地方 - 在全局 space:
<?php
namespace Languages;
use Languages\Danish; // <-- this is correct!
function toGreenlandic()
{
// ...
}
?>
我有一个脚本 A,放在命名空间 A 中。在这个脚本中,我将其中定义的所有函数包装在 class A 中。
然后我有另一个脚本 B,放在命名空间 B 中,也将脚本的所有功能包装到 class B.
class B 包含 10 个函数,而其中只有一个函数 B_1 需要访问 class A 中定义的函数。因此,我决定将 require script_A
函数内的语句 B_1.
问题是:我想在名称空间 B 中定义的 class B 的函数 B_1 中使用名称空间 A 中 class A 的函数 A_1。当我在函数 B_1:
中执行此操作时require "script_A.php";
use namespace_A\class_A;
我的语法校正器告诉我 unexpected use of "use"
。我的 require script_A
内部函数 B_1 以及随后使用函数 A_1 的唯一方法似乎是通过使用完全限定的命名空间调用 A_1:
require "script_A.php";
\namespace_A\class_A::A_1();
我只是想仔细检查一下这是否正常?真的不可能使用“使用”在其他名称空间的 PHP 函数中导入名称空间吗?还是我误解了某事?脚本 B 的完整代码示例:
namespace B;
class B {
public static function B1() {
require_once "script_A.php";
use A\classA;
}
}
我的 linter 在 use
此处报告错误。我的替代方案是下面的代码,它有效:
namespace B;
class B {
public static function B1() {
require_once "script_A.php";
\A\classA::A1();
}
}
来自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.
以下示例将显示对 use 关键字的非法使用:
<?php
namespace Languages;
function toGreenlandic()
{
use Languages\Danish; // <-- this is wrong!!!
// ...
}
?>
这是应该放置 use
的地方 - 在全局 space:
<?php
namespace Languages;
use Languages\Danish; // <-- this is correct!
function toGreenlandic()
{
// ...
}
?>