CKTIS / PHP
Sleutelwoord trait
Bundelt methoden of andere leden voor hergebruik in klassen.
Versie: PHP 8.4; repository runtime, production runtime not attested
Syntax
trait WithKey { public function key(): string { return "k"; } }Bundelt methoden of andere leden voor hergebruik in klassen. Een klasse neemt de trait op met use. In instantiemethoden is $this het object van de ontvangende klasse. Statische traitmethoden hebben geen $this. Een methode van de klasse zelf gaat voor. De trait kan niet rechtstreeks worden geïnstantieerd.
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
Voorbeelden
<?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());
Resultaat
r1 special false