我如何在包含文件中包含名称空间?

How would I include a namespace in an included file?

我目前正在构建一个项目来学习 Slim 框架。我对 Slim 有很好的基本了解,但命名空间对我来说仍然很混乱。我根据它们相关的页面(主页、关于、添加等)将我的路线存储在单独的文件中。问题是我无法在不使用

的情况下创建 RequestResponse 对象
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

在每个路由文件的顶部。有没有一种方法可以将 use 放在我的主路由文件的顶部并让每个包含的文件都使用它?

例如,我的 routes.php 文件包含在我的 start.php 文件中,后者包含在我的 index.php 中。在我的路线文件中包含每个特定路线 home.php, about.php, add.php, etc。我的 routes.php 中包含的每个文件都必须有一个 use 语句,否则我无法在没有命名空间的情况下访问 ResponseRequest

不,你不能这样做。粗鲁的解释 - "Use statement belongs to file"(如果我们不在文件中使用多个命名空间声明,则不推荐这样做)。您也不能使用 require/include.

扩展命名空间
test.php: 
    include "MyString.php"; 
    print ","; 
    print strlen("Hello world!"); 
MyString.php: 
    namespace MyFramework\String; 
    function strlen($str) { 
        return \strlen($str)*2;
    } 
    print strlen("Hello world!");

Output: 24,12

但是您可以在命名空间中实例化您的对象一次。它们将在命名空间的其他文件中可用。

test.php:
    namespace App;
    include "request.php";
    var_dump($request); //$request object is available here
request.php
    namespace App;
    use \Http\Request as Request;
    $request = new Request();

另外,Slim框架应该有依赖容器。也许你可以把你的东西放在这里。对框架不熟悉,欢迎指正。