0

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?

Community
  • 1
  • 1
diolemo
  • 2,621
  • 2
  • 21
  • 28

1 Answers1

0

Shot in the dark, but since you haven't posted what you have tried...

I think what you are looking for is__METHOD__

In your train function you can call METHOD to get the current alias.

if (__METHOD__ == "testFunction") { //has not been renamed
geggleto
  • 2,605
  • 1
  • 15
  • 18
  • I did test that but may not have made it clear in my code comments. It always returns `TestTrait::testFunction` so isn't useful. – diolemo Jan 09 '15 at 23:30