Pergunta

As far as I can tell PHP traits exist to offer pseudo multi-inheritance... and looking at them, they rather remind me of structs, except there return type is the same as functions.

ANYWAY - what can I do with a trait that I can't already do with an interface, or just another function?

Foi útil?

Solução

A trait does not carry any type information, and therefore does not have anything in common with an interface.

class Test implements TestInterface {
   use TestTrait;
}

$x = new Test;
var_dump( $x instanceof TestInterface );  // true
var_dump( $x instanceof TestTrait );      // false

All in all, traits is a way to repeat code without resorting to copy-paste.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top