如何在包含的文件中包含命名空间


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语句属于文件"(如果我们没有在文件中使用multiple命名空间声明,这是不推荐的(。也不能使用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!");

输出: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框架中应该有依赖容器。也许你可以把你的物品放在这里。不熟悉该框架,请随时纠正我的错误。