As the @Anderson Carlos Woss has already commented and practically answered your questions, I will an addendum as you can read in documentation :
What are Traits
?
Traits are mechanisms for code reuse in unique inheritance languages.
They should be used where there are no relationships and can not extend / inherit from another class. Using the example of Thiago Belem , imagine a feature of log
, where you would usually create a class for 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 have 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 behavior in 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');
}
}
Responding to your questions:
Can I use traits like this?
If language allows you to use it like that, it is something totally different. And for the second option, it's not .
Is this correct?
No, it is not correct. In the documentation itself says that you can not instantiate it on your own.
Read Horizontal Reuse to get a little better understanding of what you are proposing with Traits
.