2015-01-09 75 views
0

我有許多類使用PHP的特點。其中一些類選擇重命名特徵函數。特質中的其中一種方法想自稱。它如何自稱?如何找出重命名的內容?如何知道函數何時被別名或重命名?

<?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(); 

相關:Anyone know of a PHP Magic Constant for Trait's Redefined Name in a Class?

回答

0

在黑暗中拍攝,但因爲你還沒有發佈,你已經嘗試了什麼......

我想你在找什麼is__METHOD__

在你的火車功能,你可以撥打方法得到當前的別名。

if (__METHOD__ == "testFunction") { //has not been renamed 
+0

我做了測試,但可能沒有在我的代碼註釋中說清楚。它總是返回'TestTrait :: testFunction',所以沒用。 – diolemo 2015-01-09 23:30:30