dplp5928 2015-11-02 15:17
浏览 58
已采纳

在PHP中使用final的traits

What i want is the ability to make "final traits" with the behaviour as described below. I realise this is not possible with traits(or is it? that would make me so happy), but I'm just trying to convey what I want to do.

So, i want to have a trait that is

trait Content {
    public final function getPostContent(){ /*...*/ }
    public final function setPostContent($content){ /*...*/ }
}

What I want is

Marking the functions in the traits as final making sure that if a class uses this trait, the trait implementation is the guaranteed implementation

class MyClass {
    use Content;
    public function getPostContent() { // This should not be allowed
        return null;
    }
}

I want to be able to somehow check if a class uses a trait(i.e. $myObject instanceof Content)

class MyClass {}
class MyClassWithContent {
    use Content;
}
var_dump((new MyClass) instanceof Content); // "bool(false)"
var_dump((new MyClassWithContent) instanceof Content; // "bool(true)"

Making sure that when the trait is being used, the methods name/visibility can not be changed. So, none of this should be allowed.

class MyDeceptiveClass {
    use Content {
        Content::getPostContent as nowItsNotCalledGetPostContentAnymore();
        Content::setPostContent as protected; // And now setPostContent is protected
    }
}
  • 写回答

1条回答 默认 最新

  • dsgtew3241 2015-11-02 15:47
    关注

    Methods in traits are overwritten by methods defined in a class, even if the trait method is final:

    <?php
    trait Bar {
        final public function fizz() {
            echo "buzz
    ";
        }
    }
    
    class Baz {
        use Bar;
    
        public function fizz() {
            echo "bam
    ";
        }
    }
    
    $x = new Baz;
    $x->fizz(); // bam
    

    Taking a look at the precedence section in the traits documentation:

    An inherited member from a base class is overridden by a member inserted by a Trait. The precedence order is that members from the current class override Trait methods, which in turn override inherited methods.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。