Are traits in PHP affected by namespaces?

14,979

Solution 1

Yes, they are.

Import the trait with use outside the class for PSR-4 autoloading.

Then use the trait name inside the class.

namespace Example\Controllers;

use Example\Traits\MyTrait;

class Example {
    use MyTrait;

    // Do something
}

Or just use the Trait with full namespace:

namespace Example\Controllers;

class Example {
    use \Example\Traits\MyTrait;

    // Do something
}

Solution 2

I think they are affected as well. Look at some of the comments on the php.net page.

The first comment:

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
}
?>

Solution 3

In my experience if this piece of code you pasted resides in different files/folders and you use the spl_autoload_register function to load classes you need to do it like this:

  //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
  }

Solution 4

The documentation also says "A Trait is similar to a class", A trait is a special case of a class. So what applied to a class also applied to a trait.

Share:
14,979
learning php
Author by

learning php

Updated on July 19, 2022

Comments

  • learning php
    learning php almost 2 years

    From the PHP documentation:

    only four types of code are affected by namespaces: classes, interfaces, functions and constants.

    But, it seems to me that TRAITS are also affected:

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

    Am I wrong?