Baza znanjaCentar za ispite
HRHrvatski
Odaberi jezik13

CKTIS / PHP

Ključna riječ trait

Okuplja metode ili druge članove za ponovnu uporabu u razredima.

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

Sintaksa

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

Okuplja metode ili druge članove za ponovnu uporabu u razredima. Razred uključuje trait s use. U metodama instance $this je objekt primajućeg razreda. Statičke metode traitova nemaju $this. Metoda deklarirana u razredu ima prednost. Sam trait nije moguće instancirati.

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

Primjeri

<?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

Izvori