Why does method renaming not work in PHP traits?

I am using PHP 7.1.0.

Say we have a trait, we use it inside the class and rename the imported method:

trait T
{
    public function A() {
        echo ".";
    }
}

class C
{
    use T {
        A as B;
    }
}

$c = new C();
$c->B();
$c->A(); // Why does it work?

Why is PHP still allowing me to use the old method name ( Ain this case)?

This is really a pain, because in more complex examples you cannot rely on the renaming of the method - and therefore, you may unexpectedly get the error "incompatible declarations":

class BaseSrc
{
}

trait BaseTrait
{
    public function init(BaseSrc $baseSrc)
    {
        echo "Init Base";
    }
}

class Base
{
    use BaseTrait {
        BaseTrait::init as initBase;
    }
}

$base = new Base();
$base->initBase(new BaseSrc());
$base->init(new BaseSrc()); // WHY DOES IT WORK?????

class MainSrc extends BaseSrc
{
}

trait MainTrait
{
    use BaseTrait {
        BaseTrait::init as initBase;
    }

    public function init(MainSrc $mainSrc)
    {
        $this->initBase($mainSrc);
        echo "Init Main";
    }
}

// Warning: Declaration of MainTrait::init(MainSrc $mainSrc) should be compatible with Base::init(BaseSrc $baseSrc)
class Main extends Base
{
    use MainTrait;
}

, . init() initBase() Base BaseTrait MainTrait, , (BaseTrait::init()) MainTrait::init(). , PHP , . , init as initBase - init Base!

BaseTrait:: init() BaseTrait:: initBase() ( use)?

PHP ? - ?

+6
1

; PHP :

Aliased_Talker as B bigTalk .

:

as . , as .

, as , . .

0

Source: https://habr.com/ru/post/1017066/


All Articles