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?
only four types of code are affected by namespaces: classes, interfaces, functions and constants.
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.
Note: Namespace names are case-insensitive.
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.
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
}
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
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With