用PHP类扩展特性? [英] Extend Traits with Classes in PHP?

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

问题描述

为什么我们不允许在PHP中使用类扩展特性?

Why we are not allowed to extend Traits with Classes in PHP?

例如:

Trait T { }

Class C use T {}
/* or */
Class C extends T {}

此类语法是否存在潜在冲突?我不这么认为.

Is there any potential conflict for such syntax? I do not think so.

推荐答案

PHP手册指出:

特性是一种在PHP等单一继承语言中重用代码的机制.特性旨在通过使开发人员在生活在不同类层次结构中的几个独立类中自由重用方法集,从而减少单一继承的某些限制.特性和类的组合的语义被定义为可以降低复杂性,并且避免了与多重继承和Mixins相关的典型问题.

Traits is a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins.

如果您想扩展特征,那么它可能应该是一个类.如果在一个类中有一组要在其他类中使用的方法,但是扩展该类(例如class Animal extends Vehicle)感觉不合适,那么在PHP 5.4中,它可以很好地用作特征.

If you're looking to extend a trait, then it should probably be a class. If you have a set of methods in one class that you want to use in others, but it feels inappropriate to extend the class (eg. class Animal extends Vehicle), then in PHP 5.4 it could work well as a trait.

要更直接地回答问题,您无需扩展"特征,但可以创建本身使用其他特征的特征.按照PHP手册:

To answer the question more directly, you don't 'extend' a trait, but you can create traits which themselves use other traits. As per the PHP manual:

trait Hello {
    public function sayHello() {
        echo 'Hello ';
    }
}

trait World {
    public function sayWorld() {
        echo 'World!';
    }
}

trait HelloWorld {
    use Hello, World;
}

class MyHelloWorld {
    use HelloWorld;
}

您可以认为这是在逻辑组中保持特征并引入一些模块化的方法.

You can consider this to be a way to maintain your traits in logical groups, and to introduce some modularity.

看过一些评论后,我认为值得一提的是,在基类中使用trait也意味着trait在扩展它的任何类中,并且trait的功能优先于基类.将其放在子类中只会使该特性的功能对父/基类不可用.

having seen some of the comments, I think it's worthwhile to note that using a trait in a base class also means that trait is in any class that extends it, and the trait's functions take precedence over the base class'. Putting it in the child class would merely make the trait's functions unavailable to the parent/base class.

Parent > Trait > Child

http://php.net/manual/en/language.oop5.traits.php

这篇关于用PHP类扩展特性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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