Are there any contradictions to use traits to inject helper methods like this?
class Foo { use Helper\Array; function isFooValid(array $foo) { return $this->arrayContainsOnly('BarClass', $foo); } }
That's the idea with traits.
However you should still keep an eye out for coupled code. If Helper\Array
is a completely different namespace from what Foo
is in you might want to re-think this particular approach.
Traits have been added to PHP for a very simple reason: PHP does not support multiple inheritance. Simply put, a class cannot extends more than on class at a time. This becomes laborious when you need functionality declared in two different classes that are used by other classes as well, and the result is that you would have to repeat code in order to get the job done without tangling yourself up in a mist of cobwebs.
Enter traits. These allow us to declare a type of class that contains methods that can be reused. Better still, their methods can be directly injected into any class you use, and you can use multiple traits in the same class. Let's look at a simple Hello World example.
<?php
trait SayHello
{
private function hello()
{
return "Hello ";
}
private function world()
{
return "World";
}
}
trait Talk
{
private function speak()
{
echo $this->hello() . $this->world();
}
}
class HelloWorld
{
use SayHello;
use Talk;
public function __construct()
{
$this->speak();
}
}
$message = new HelloWorld(); // returns "Hello World";
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