Base de conocimientosCentro de exámenes
ESEspañol
Elegir idioma13

CKTIS / PHP

Palabra clave trait

Agrupa métodos u otros miembros reutilizables en clases.

Versión: PHP 8.4; repository runtime, production runtime not attested

Sintaxis

trait WithKey { public function key(): string { return "k"; } }

Agrupa métodos u otros miembros reutilizables en clases. La clase importa el trait con use. En métodos de instancia $this designa el objeto de la clase receptora. Los métodos estáticos del trait carecen de $this. Un método declarado en la clase tiene prioridad. El propio trait no se puede instanciar.

trait WithKey {public function key():string{return $this->prefix."1";}}
class Row {use WithKey; public string $prefix="r";} class Special {use WithKey; public function key():string{return "special";}}
echo (new Row())->key()," ",(new Special())->key();
trait Scope {public static function bound():bool{return isset($this);}} class Reader {use Scope;} echo "\n",json_encode(Reader::bound());
r1 special
false

Ejemplos

<?php
trait WithKey {public function key():string{return $this->prefix."1";}}
class Row {use WithKey; public string $prefix="r";} class Special {use WithKey; public function key():string{return "special";}}
echo (new Row())->key()," ",(new Special())->key();
trait Scope {public static function bound():bool{return isset($this);}} class Reader {use Scope;} echo "\n",json_encode(Reader::bound());

Resultado

r1 special
false

Fuentes