我有一个名为 test.php 的命名空间文件,其中包含一个函数和一个类:
namespace Test;
function testFunc(){}
class TestClass{}
然后,如果在另一个文件中我“使用”了这两个命名空间元素,则该类有效但函数无效:
use Test\testFunc,
Test\TestClass;
include "test.php";
new TestClass();
testFunc();
TestClass 对象创建的很好,但是我得到了 testFunc() 的 fatal error :
Fatal error: Call to undefined function testFunc()
我认为命名空间支持函数。我做错了什么?
编辑: 此处解释 - http://www.php.net/manual/en/language.namespaces.faq.php#language.namespaces.faq.nofuncconstantuse
最佳答案
参见 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"
和
// 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"
关于php - 无法在 PHP 中导入/使用命名空间函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5647598/