CKTIS / PHP
Keyword trait
Package methods or other members for horizontal reuse.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
trait WithKey { public function key(): string { return "k"; } }Package methods or other members for horizontal reuse. A class imports a trait using use, and an imported instance method runs with the receiving object as $this. A static trait method has no $this. A method declared by the class overrides the imported one. A trait cannot itself be instantiated.
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
Examples
<?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());
Result
r1 special false