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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?