无法在PHP中导入/使用命名空间函数

Gnu*_*fo1 5 php namespaces

我有一个名为test.php的命名空间文件,它带有一个函数和一个类:

namespace Test;
function testFunc(){}
class TestClass{}
Run Code Online (Sandbox Code Playgroud)

然后,如果在另一个文件中我"使用"这两个命名空间元素,则该类可以工作,但不能使用该函数:

use Test\testFunc,
    Test\TestClass;

include "test.php";
new TestClass();
testFunc();
Run Code Online (Sandbox Code Playgroud)

TestClass对象创建正常,但我得到testFunc()的致命错误:

Fatal error: Call to undefined function testFunc()
Run Code Online (Sandbox Code Playgroud)

我认为命名空间支持函数.我究竟做错了什么?

编辑:这里的解释 - http://www.php.net/manual/en/language.namespaces.faq.php#language.namespaces.faq.nofuncconstantuse

Tre*_*non 3

请参阅http://php.net/manual/en/language.namespaces.rules.php,特别注意:

<?php
namespace A;
use B\D, C\E as F;

// function calls

foo();      // first tries to call "foo" defined in namespace "A"
            // then calls global function "foo"

\foo();     // calls function "foo" defined in global scope

my\foo();   // calls function "foo" defined in namespace "A\my"

F();        // first tries to call "F" defined in namespace "A"
            // then calls global function "F"
Run Code Online (Sandbox Code Playgroud)

// static methods/namespace functions from another namespace

B\foo();    // calls function "foo" from namespace "A\B"

B::foo();   // calls method "foo" of class "B" defined in namespace "A"
            // if class "A\B" not found, it tries to autoload class "A\B"

D::foo();   // using import rules, calls method "foo" of class "D" defined in namespace "B"
            // if class "B\D" not found, it tries to autoload class "B\D"

\B\foo();   // calls function "foo" from namespace "B"

\B::foo();  // calls method "foo" of class "B" from global scope
            // if class "B" not found, it tries to autoload class "B"
Run Code Online (Sandbox Code Playgroud)

  • 所以基本上你不能像类一样导入函数?该示例也没有明确说明常量,我认为它们是相同的?实际上,这里有一个更清晰的解释 - http://www.php.net/manual/en/language.namespaces.faq.php#language.namespaces.faq.nofuncconstantuse (3认同)