Baza znanjaIzpitno središče
SLSlovenščina
Izberi jezik13

CKTIS / PHP

Ključna beseda trait

Združi metode ali druge člane za ponovno uporabo v razredih.

Različica: PHP 8.4; repository runtime, production runtime not attested

Sintaksa

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

Združi metode ali druge člane za ponovno uporabo v razredih. Razred vključi trait z use. V metodah primerka je $this objekt prejemnega razreda. Statične metode traitov nimajo $this. Metoda, deklarirana neposredno v razredu, ima prednost. Sam trait ne more imeti primerkov.

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

Primeri

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

Rezultat

r1 special
false

Viri