Just like the @Anderson Carlos Woss has already commented and has practically answered your questions, I will make an addendum as you can read in documentation:
What are Traits
?
Traits are mechanisms for reusing code in single inheritance languages.
They should be used where there are no relations and cannot/should extend/inherit from another class. Using the example of Thiago Belem , imagine a feature of log
, where you would usually create a class to manipulate this:
class Log {
public function log($message) {
// Salva $message em um log de alguma forma
}
}
And to use it, you would do something like:
class Usuario extends Model {
protected $Log;
public function __construct() {
$this->Log = new Log();
}
public function save() {
// Salva o usuário de alguma forma
// ...
// Salva uma mensagem de log
$this->Log->log('Usuário criado');
}
}
See the work you need to use this feature, when you could simplify using Traits
:
trait Log {
public function log($message) {
// Salva $message em um log de alguma forma
}
}
Defining the behavior in the class:
class Usuario extends Model {
use Log;
public function save() {
// Salva o usuário de alguma forma
// ...
// Salva uma mensagem de log
$this->log('Usuário criado');
}
}
Answering your own questions:
I can wear the traits like this ?
If the language allows to use this is one thing, if MUST is another totally different. And for the second option, it is nay.
that is correct ?
No, it is not correct. In the documentation itself it says that it is not possible to instance it on its own.
Read on Horizontal Reuse to understand a little better what is proposed with the use of Traits
.
The first question you should ask is why you are doing this. Why not use the right mechanism? If you really have a reason to do this, you tried, it worked?
– Maniero
Trait
is a form of structuring for related and independent business rules. By definition, atrait
should not exist without a class, because the first defines the behavior of the second, so I believe that no, you should not do this.– Woss
I understood that this is why I created the traits, because some classes needed new functionalities and I realized that these functionalities could exist in other classes, which is what really happened, only I used them independently of the classes, so now I’m gonna fix it.
– Lucas Lima
I also realized that we can not group them in a namespace if we have to give a use in the trait within the class.
– Lucas Lima