I have a PHP trait thats used in many classes. Some of those classes choose to rename the trait functions. One of the methods in the trait would like to call itself. How can it call itself? How can it find out what is has been renamed to?
<?php
Trait TestTrait
{
protected function testFunction()
{
// Calls TestClass function
// instead of the trait function.
$this->testFunction();
// Calls TestClass function
// instead of the trait function.
static::testFunction();
// Fatal error: Call to protected method
// TestTrait::testFunction() from context 'TestClass'
TestTrait::testFunction(); # __METHOD__
// This works but requires that
// the trait know that the function
// has been renamed. How can we
// determine if has been renamed?
$this->traitTestFunction();
}
}
class TestClass
{
use TestTrait
{
testFunction as traitTestFunction;
}
function testFunction()
{
$this->traitTestFunction();
}
}
$test = new TestClass();
$test->testFunction();
Related: Anyone know of a PHP Magic Constant for Trait's Redefined Name in a Class?