2011-04-13 39 views
5
導入/使用一個命名空間功能

我得叫test.php的具有功能和類的命名空間文件:不能在PHP

namespace Test; 
function testFunc(){} 
class TestClass{} 

那麼如果在另一個文件I「用」這兩個命名空間的元素,類作品,但不是功能:

use Test\testFunc, 
    Test\TestClass; 

include "test.php"; 
new TestClass(); 
testFunc(); 

的TestClass的對象被創建很好,但我得到testFunc()一個致命的錯誤:

Fatal error: Call to undefined function testFunc() 

我認爲功能是由命名空間支持的。我究竟做錯了什麼?

編輯:說明這裏 - http://www.php.net/manual/en/language.namespaces.faq.php#language.namespaces.faq.nofuncconstantuse

回答

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" 

而且

// 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" 
+3

所以基本上你不能導入功能一樣類?這個例子也沒有說明常量,我假設它們是相同的?其實,這裏有一個更清晰的解釋 - http://www.php.net/manual/en/language.namespaces.faq.php#language.namespaces.faq.nofuncconstantuse – Gnuffo1 2011-04-13 10:30:30