Traits reuse implementation
Lesson 39 of 48 in Coddy's PHP for GDScript Developers course.
GDScript reuses behavior through inheritance and composed helper objects rather than PHP trait syntax. PHP traits insert reusable methods into a class through use. They are not instantiable objects or interface parameter types, and method conflicts need explicit resolution.
A trait supplies reusable methods to classes with use. It cannot be instantiated and is not an interface type for parameters. Traits resolve implementation reuse separately from inheritance. When traits collide, resolve precedence explicitly with insteadof and aliases with as rather than relying on include order.
GDScript program
extends SceneTree
class Greeting:
func hello():
return "hello"
class Host:
var greeting = Greeting.new()
func hello():
return greeting.hello()
func _init():
print(Host.new().hello())
quit()
Source output:
helloPHP program
Greeting.php
<?php
declare(strict_types=1);
trait Greeting {public function hello():string{return "hello";}}
Host.php
<?php
declare(strict_types=1);
require_once __DIR__."/Greeting.php";class Host {use Greeting;}
demo.php
<?php
declare(strict_types=1);
require_once __DIR__."/Host.php";echo (new Host())->hello(),"\n";
PHP output:
helloChallenge
EasyInput is an ASCII string. Trimmed trait supplies clean(string):string returning trim. Note and Label both use Trimmed. Driver prints cleaned text from both separated by |.
The supplied main script reads one JSON value from standard input, checks the named public APIs, and prints the result. Implement the module declarations without printing; do not replace the launcher or read input from a module. Input satisfies the stated types and bounds.
Edit Trimmed.php, Note.php, Label.php. main.php is the locked entry file. Dependencies use require_once __DIR__ with a relative filename.
Try it yourself
<?php
declare(strict_types=1);
require_once __DIR__."/Trimmed.php";
require_once __DIR__."/Note.php";
require_once __DIR__."/Label.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
ensure((new Note())->clean(" z ")==="z" && (new Label())->clean(" y ")==="y","shared trait");
echo (new Note())->clean($input)."|".(new Label())->clean($input),"\n";
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in PHP for GDScript Developers
1Values and output
Modules and first runFormatting returned textAssignments and variablesDivision and conversionStrings and byte lengthsExplicit Boolean rulesRecap: receipt text4Functions and modules
Functions and return typesDefaults and named callsVariadic argumentsCallbacks and capturesrequire_once and scopeRecap: integer cents2Control flow
Branches and precedenceStrict match expressionsLoops and early exitsKeys and iterationRecap: shipping rules5Errors and boundaries
Exceptions and stateStrict input validationNull is not falsyRecap: validate a batch8Sharing and identity
Traits reuse implementationObject handles and identityCloning nested objectsRecap: shared registryPractice on your own: Online PHP compiler