在if/else语句中使用名称空间 [英] Using namespace in if / else statements

查看:82
本文介绍了在if/else语句中使用名称空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在操纵同一文件来管理两个外部api类.

I am manipulating the same file to manage two external api classes.

一个api类基于命名空间,另一个则不基于命名空间.

One api class is based on namespaces, the other one is not.

我想做的是这样的:

if($api == 'foo'){
   require_once('foo.php');
}
if($api == 'bar'){
   require_once('bar.php');
   use xxxx\TheClass;
}

问题是当我这样做时,会返回以下错误消息:

The problem is that when I do so, the following error message is returned:

Parse error: syntax error, unexpected T_USE in etc...

问题1:我是否必须使用两个不同的文件来管理这两个类,或者在使用文档中的名称空间时是否可以同时管理这两个类?从我看来,似乎并非如此.

Question 1: Do I have to use two different files to manage the two classes or is it possible to manage both while using namespaces in the document? From what I see, it does not seem to be.

问题2:为什么不能在if()语句中使用命名空间?

Question 2: Why namespaces could not be used inside if() statements?

谢谢您的帮助

推荐答案

请参阅 导入的作用域规则

必须在文件的最外部作用域(全局作用域)或内部命名空间声明中声明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.

所有use所做的只是将符号名称导入到当前名称空间中.我只是忽略了导入,而是使用完全限定的类名,例如

All use does is import a symbol name into the current namespace. I would just omit the import and use the fully qualified class name, eg

switch ($api) {
    case 'foo' :
        require_once('foo.php');
        $someVar = new SomeClass();
        break;
    case 'bar' :
       require_once('bar.php');
       $someVar = new \xxxx\TheClass();
       break;
   default :
       throw new UnexpectedValueException($api);
}

您还可以简单地将use语句添加到脚本顶部.添加它不会使您包含任何文件,也不需要知道该符号,例如

You can also simply add the use statement to the top of your script. Adding it does not commit you to including any files and it does not require the symbol to be known, eg

use xxxx\TheClass;

switch ($api) {
    case 'foo' :
        require_once('foo.php');
        $someVar = new SomeClass();
        break;
    case 'bar' :
       require_once('bar.php');
       $someVar = new TheClass(); // imported above
       break;
   default :
       throw new UnexpectedValueException($api);
}

这篇关于在if/else语句中使用名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆