php - 在命名空间 B 的函数中使用命名空间 A 的函数

标签 php namespaces

我有一个脚本 A,放置在命名空间 A 中。在这个脚本中,我将其中定义的所有函数都封装在一个类 A 中。
然后我有另一个脚本 B,放置在命名空间 B 中,也将脚本的所有功能包装到类 B 中。
类 B 包含 10 个函数,而其中只有一个函数 B_1 需要访问类 A 中定义的函数。因此,我决定放置 require script_A该函数 B_1 中的语句。
问题是:我想在命名空间 B 中定义的类 B 的函数 B_1 中使用命名空间 A 中的类 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();
我只是想仔细检查一下这是否正常?真的不能使用“use”在其他命名空间的 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应该放在 - 在全局空间中:
<?php
namespace Languages;
use Languages\Danish; // <-- this is correct!

function toGreenlandic()
{
    // ...
}
?>

关于php - 在命名空间 B 的函数中使用命名空间 A 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65279566/

相关文章:

php - 使用 php 客户端使用 Web 服务(Soap)

perl - 从不同命名空间中所需的文件中调用子例程

asp.net - 我更换了计算机,但在尝试构建项目时遇到了一堆命名空间错误?

php - spl_autoloader 未加载任何类

javascript - 无法在 laravel mix 中添加 bootstrap.min.js

php - 嵌套在 if 语句中的 MySQL 查询 - PHP

php - 自定义wordpress小部件发生错误

php - 在Laravel 5.7中更改(电子邮件)按钮的颜色

Javascript 并从另一个引用一个命名空间属性

php - Laravel 基于var 调用静态函数