Skip to content

Instantly share code, notes, and snippets.

@giuseppe998e
Created October 26, 2022 23:12
Show Gist options
  • Save giuseppe998e/dc026ade0dda0fd6f9439d8b50e7bfff to your computer and use it in GitHub Desktop.
Save giuseppe998e/dc026ade0dda0fd6f9439d8b50e7bfff to your computer and use it in GitHub Desktop.
Test of PHP traits behavior using "self" and "static" keywords
<?php declare(strict_types = 1);
// Tried on PHP 8.0.25
// Trait
trait TestTrait {
public static function spawnSelf(): self {
return new self();
}
public static function spawnStatic(): static {
return new static();
}
}
// Test classes
class TestClass {
use TestTrait;
}
class TestClassChild extends TestClass {
// The next line changes the behavior, see "Result #2".
//use TestTrait;
}
// Util function
function class_str(object $class): string {
return $class::class . PHP_EOL;
}
// Main code
echo 'TestClass::spawnSelf: ' . class_str(TestClass::spawnSelf());
echo 'TestClass::spawnStatic: ' . class_str(TestClass::spawnStatic());
echo PHP_EOL;
echo 'TestClassChild::spawnSelf: ' . class_str(TestClassChild::spawnSelf());
echo 'TestClassChild::spawnStatic: ' . class_str(TestClassChild::spawnStatic());
/*
>>> Result:
TestClass::spawnSelf: TestClass
TestClass::spawnStatic: TestClass
TestClassChild::spawnSelf: TestClass
TestClassChild::spawnStatic: TestClassChild
>>> Result #2:
// ...
TestClassChild::spawnSelf: TestClassChild
TestClassChild::spawnStatic: TestClassChild
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment