CKTIS / PHP
Ключова дума trait
Обединява методи или други членове за повторно използване в класове.
Версия: PHP 8.4; repository runtime, production runtime not attested
Синтаксис
trait WithKey { public function key(): string { return "k"; } }Обединява методи или други членове за повторно използване в класове. Класът включва trait с use. В методи на екземпляр $this е обектът от приемащия клас. В статичните методи на trait няма $this. Метод, деклариран в самия клас, има предимство. Самият trait не може да се инстанцира.
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
Примери
<?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());
Резултат
r1 special false