Use final on traits in PHP

爱⌒轻易说出口 提交于 2021-01-28 02:14:01

问题


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:


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\n";
    }
}

class Baz {
    use Bar;

    public function fizz() {
        echo "bam\n";
    }
}

$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.



来源:https://stackoverflow.com/questions/33480919/use-final-on-traits-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!