首页 > 解决方案 > php需要文件类命名空间不起作用

问题描述

我有两个班级。我想通过在 Bar 类中包含 Foo 来运行这些类。它在没有命名空间的情况下运行良好。

<?php

class Foo
{

    public static function test()
    {
        echo 'test';
    }
}

应用程序.php

Foo::test();

酒吧班

class Bar
{

    public function run()
    {
        require('app.php');
    }
}



$bar = new Bar();
$bar->run();

当我使用命名空间时,它不起作用。

<?php
namespace example;

class Foo{

    public static function test(){
        echo 'test';
    }
}

应用程序.php

Foo::test();

酒吧班

namespace example;

use example\Foo;

class Bar{

    public function run(){
     Foo::test(); // its works
         require('app.php'); //  Fatal error: Uncaught Error: Class 'Foo' not found
    }
}


$bar = new \example\Bar();
$bar->run();

当我将命名空间添加到 app.php 文件时,它可以工作。

应用程序.php

use example\Foo;
Foo::test();

有没有办法在不添加命名空间的情况下运行文件?

我是通过翻译用英文写的。我希望你明白。

标签: phpnamespacesincluderequire

解决方案


推荐阅读