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

查看:27
本文介绍了在 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 xxxxTheClass;
}

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

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 xxxxTheClass();
       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 xxxxTheClass;

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天全站免登陆