在 PHP 中对特征使用 final [英] Use final on traits in PHP

查看:45
本文介绍了在 PHP 中对特征使用 final的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要的是通过如下所述的行为制作最终特征"的能力.我意识到这是不可能的(或者是吗?那会让我很高兴),但我只是想传达我想做的事情.

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.

所以,我想要一个特质

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

我想要的是

将 trait 中的函数标记为 final 确保如果一个类使用这个 trait,则 trait 实现是有保证的实现

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;
    }
}

我希望能够以某种方式检查类是否使用特征(即 $myObject instanceof Content)

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
    }
}

推荐答案

traits 中的方法会被类中定义的方法覆盖,即使 trait 方法是 final:

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

查看优先级部分 在特性文档中:

从基类继承的成员被 Trait 插入的成员覆盖.优先顺序是当前类的成员覆盖 Trait 方法,然后覆盖继承的方法.

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.

这篇关于在 PHP 中对特征使用 final的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆