CKTIS / PHP
Klíčové slovo trait
Seskupuje metody či jiné členy pro opakované použití ve třídách.
Verze: PHP 8.4; repository runtime, production runtime not attested
Syntaxe
trait WithKey { public function key(): string { return "k"; } }Seskupuje metody či jiné členy pro opakované použití ve třídách. Třída načte trait pomocí use. V instančních metodách je $this objekt přijímající třídy. Statické metody traitu nemají $this. Metoda deklarovaná přímo ve třídě má přednost. Samotný trait nelze instanciovat.
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
Pří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ýsledek
r1 special false