在函数内部使用 php 命名空间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18227439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use php namespace inside function
提问by westnblue
I get a parse error when trying to use a name space inside my own function
尝试在我自己的函数中使用名称空间时出现解析错误
require('/var/load.php');
function go(){
use test\Class;
$go = 'ok';
return $go;
}
echo go();
回答by Nishant
From 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 关键字必须在文件的最外层作用域(全局作用域)或命名空间声明内声明。这是因为导入是在编译时而不是运行时完成的,所以它不能是块作用域
So you should put like this, use should specified at the global level
所以你应该像这样,使用应该在全局级别指定
require('/var/load.php');
use test\Class;
function go(){
$go = 'ok';
return $go;
}
echo go();
Check the example 5 in the below manual Please refer to its manual at http://php.net/manual/en/language.namespaces.importing.php
检查以下手册中的示例 5 请参阅其手册http://php.net/manual/en/language.namespaces.importing.php
回答by lonesomeday
From the manual:
从手册:
The
use
keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations.
该
use
关键字必须在一个文件中(全球范围)或命名空间内声明的最外层范围声明。
回答by Robert Sinclair
From what I gather a lot of people are getting this when including a separate function file and trying to use the static method inside that function.. For example in index.php
从我收集到的很多人在包含一个单独的函数文件并尝试在该函数中使用静态方法时都会得到这个。例如在index.php 中
namespace foo/bar
require('func.php')
f();
and in func.php
并在func.php
function f() {
StaticClass::static_method();
}
you simply need to declare namespace foo/bar in func.php(same like how you declared it in index.php)so instead of the above it should look like:
您只需要在func.php 中声明命名空间 foo/bar (与您在index.php 中声明它的方式相同),因此它应该如下所示:
namespace foo\bar
function f() {
StaticClass::static_method();
}
to avoid errors like:
避免以下错误:
Fatal error: Uncaught Error: Class 'StaticClass' not found in func.php
致命错误:未捕获的错误:在 func.php 中找不到类“StaticClass”
It's obvious now but I was confused why func.php does not carry over the namespace declaration inside the file that 'requires' func.php
现在很明显,但我很困惑为什么 func.php 没有在“需要”func.php 的文件中继承命名空间声明