dqqfuth6736 2018-05-16 15:26
浏览 33
已采纳

PHP中抽象特征方法的实现

I have a class that looks like this. I will also paste it below for reference:

<?php

trait T1
{
    abstract protected function _doStuff();
}

trait T2
{
    protected function _doStuff()
    {
        echo "Doing stuff in trait
";
    }
}

class C
{
    use T1 {
        _doStuff as _traitDoStuff;
    }

    use T2 {
        _doStuff as _traitDoStuff;
    }

    protected function _doStuff()
    {
        echo "Doing stuff in class
";

        $this->_traitDoStuff();
    }
}

Here's what's happening here:

  1. T1::_doStuff() is used, and aliased as _traitDoStuff(). As per PHP docs, this does not rename the method, but only adds an alias. So at this point, both _doStuff() and _traitDoStuff() exist as abstract protected methods.
  2. T2::_doStuff() is used, and aliased as _traitDoStuff(). As per PHP docs, due to precedence, both are overridden by methods of T2. So at this point, T1::_doStuff() no longer exists. Even if it would, it would be implemented by T2::_doStuff().
  3. C implements _doStuff(), which calls _traitDoStuff(). At this point, regardless of which implementation of _doStuff() is used, it is obvious that this method is implemented, so the contract defined by T1::_doStuff() is satisfied, or doesn't exist.

And yet, when I run this, it gives the following error:

Fatal error: Class C contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (C::_doStuff)

As can be seen from 3v4l, this manifests everywhere from PHP 5.4 to 7.2, which kinda hints that this is not an early trait bug. Can somebody please explain this to me?

Update

Apparently, I just forgot to specify the method that I am aliasing, i.e. T1::_doStuff as _traitDoStuff.

  • 写回答

2条回答 默认 最新

  • doubiao7267 2018-05-16 15:41
    关注

    Something like that maybe ?

    <?php
    
    trait T1
    {
        abstract protected function _doStuff();
    }
    
    trait T2
    {
        protected function _doStuff()
        {
            echo "Doing stuff in trait
    ";
        }
    }
    
    class C
    {
        use T1 {
            T1::_doStuff as _traitDoStuff;
        }
    
        use T2 {
            T2::_doStuff as _traitDoStuff;
        }
    
        protected function _doStuff()
        {
            echo "Doing stuff in class
    ";
    
            $this->_traitDoStuff();
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站