Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / PHP

Słowo kluczowe trait

Grupuje metody lub inne składowe do ponownego użycia w klasach.

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

Składnia

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

Grupuje metody lub inne składowe do ponownego użycia w klasach. Klasa dołącza cechę przez use. W metodach instancji $this wskazuje obiekt klasy korzystającej z cechy. W statycznych metodach cechy $this jest niedostępne. Metoda zadeklarowana w klasie ma pierwszeństwo przed metodą cechy. Samej cechy nie można instancjonować.

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

Przykłady

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

Wynik

r1 special
false

Źródła