在函数内部使用 php 命名空间

2022-01-14 00:00:00 function namespaces php

尝试在我自己的函数中使用名称空间时出现解析错误

I get a parse error when trying to use a name space inside my own function

require('/var/load.php');

function go(){

  use testClass;

    $go = 'ok';
    return $go;
}

    echo go();

推荐答案

来自 导入范围规则

use 关键字必须声明在文件的最外层范围内(全局范围)或内部命名空间声明.这是因为导入是在编译时而不是运行时完成的,所以它不能块作用域

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

所以你应该这样说,应该在全局级别指定使用

So you should put like this, use should specified at the global level

require('/var/load.php');
use testClass;

function go(){
    $go = 'ok';
    return $go;
}
echo go();

查看以下手册中的示例 5请参阅其手册 http://php.net/manual/en/language.namespaces.importing.php

Check the example 5 in the below manual Please refer to its manual at http://php.net/manual/en/language.namespaces.importing.php

相关文章