Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are traits in PHP affected by namespaces?

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?

like image 819
learning php Avatar asked Nov 03 '13 05:11

learning php


People also ask

Which of the following elements are affected by namespaces in PHP?

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

What problems has namespace solved in PHP?

Namespaces are qualifiers that solve two different problems: They allow for better organization by grouping classes that work together to perform a task. They allow the same name to be used for more than one class.

Is PHP namespace case sensitive?

Note: Namespace names are case-insensitive.

How do traits work in PHP?

In PHP, a trait is a way to enable developers to reuse methods of independent classes that exist in different inheritance hierarchies. Simply put, traits allow you to create desirable methods in a class setting, using the trait keyword. You can then inherit this class through the use keyword.


2 Answers

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
}
like image 104
Lucas Bustamante Avatar answered Oct 02 '22 11:10

Lucas Bustamante


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
}
?>
like image 28
quickshiftin Avatar answered Oct 02 '22 10:10

quickshiftin