Znalostná bázaCentrum skúšok
SKSlovenčina
Vybrať jazyk13

CKTIS / PHP

Kľúčové slovo trait

Zoskupuje metódy či iné členy na opätovné použitie v triedach.

Verzia: PHP 8.4; repository runtime, production runtime not attested

Syntax

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

Zoskupuje metódy či iné členy na opätovné použitie v triedach. Trieda získa trait cez use. V inštančných metódach je $this objekt prijímajúcej triedy. Statické metódy traitov nemajú $this. Metóda deklarovaná priamo v triede má prednosť. Samotný trait nemožno inštanciovať.

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

Príklady

<?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());

Výsledok

r1 special
false

Zdroje