2013-11-03 12 views
5

Dalla documentazione di PHP:I caratteri in PHP sono influenzati dagli spazi dei nomi?

solo quattro tipi di codice sono affetti da spazi dei nomi: classi, interfacce, funzioni e costanti.

Ma, mi sembra che i tratti sono anche colpiti:

namespace FOO; 

trait fooFoo {} 

namespace BAR; 

class baz 
{ 
    use fooFoo; // Fatal error: Trait 'BAR\fooFoo' not found in 
} 

mi sbaglio?

+0

Sembrano essere così messi il percorso completo e iniziano con "\" use \ FOO \ fooFoo; – tristanbailey

risposta

2

Penso che siano interessati anche loro. Guarda alcuni dei commenti on the php.net page.

Il primo commento:

Note that the "use" operator for traits (inside a class) and the "use" operator for namespaces (outside the class) resolve names differently. "use" for namespaces always sees its arguments as absolute (starting at the global namespace): 

<?php 
namespace Foo\Bar; 
use Foo\Test; // means \Foo\Test - the initial \ is optional 
?> 

On the other hand, "use" for traits respects the current namespace: 

<?php 
namespace Foo\Bar; 
class SomeClass { 
    use Foo\Test; // means \Foo\Bar\Foo\Test 
} 
?> 
2

Nella mia esperienza, se questo pezzo di codice vi risiede incollato in diversi file/cartelle e si utilizza la funzione spl_autoload_register per caricare le classi che devi fare in questo modo:

//file is in FOO/FooFoo.php 
    namespace FOO; 
    trait fooFoo {} 

    //file is in BAR/baz.php 
    namespace BAR; 
    class baz 
    { 
    use \FOO\fooFoo; // note the backslash at the beginning, use must be in the class itself 
    }