• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

php中trait是什么?php中trait的简单介绍

php 搞代码 3年前 (2022-01-21) 30次浏览 已收录 0个评论

本篇文章给大家带来的内容是关于php中trait是什么?php中trait的简单介绍,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

什么是 trait?

看看 PHP 官网的介绍。

自 PHP 5.4.0 起,PHP 实现了一种代码复用的方法,称为 trait。

Trait 是为类似 PHP 的单继承语言而准备的一种代码复用机制。Trait 为了减少单继承语言的限制,使开发人员能够自由地在不同层次结构内独立的类中复用 method。Trait 和 Class 组合的语义定义了一种减少复杂性的方式,避免传统多继承和 Mixin 类相关典型问题。

Trait 和 Class 相似,但仅仅旨在用细粒度和一致的方式来组合功能。 无法通过 trait 自身来实例化。它为传统继承增加了水平特性的组合;也就是说,应用的几个 Class 之间不需要继承。

例子1

手机和汽车都有 GPS 功能,GPS 是用来定位的功能的,因此功能应该是统一的。手机 和 汽车 除了 GPS 功能外,基本没有什么相同之处,因此不能使用继承。而接口的话,我认为不同的类去实现接口时,接口的实现可能是不同的,但是 GPS 的功能就是用来定位的。因此使用 trait ,而不使用 class 和 interface,这是我的理解,不知道是否正确。

gps.php 的定义:

<?phptrait Gps {    public function gps() {        echo 'i can gps';    }}

使用 trait 定义了一个 GPS 的 trait 用于复用,它的关键字是 trait 。然后在 car.php 和 mobile.php 中进行引用。

car.php 的定义:

class Car {    use gps;    public function move() {        echo 'i can move';    }}

mobile.php 的定义:

<?phpclass Mobile {    use gps;    public function tel() {        echo 'i can tel';    }}

在 car.php 和 mobile.php 中,使用 use 关键字引入了 gps 的 trait ,这样在 car 和 mobile 中就可以调用 gps() 这个方法了。

test.php 进行测试:

<?phprequire_once('gps.php');require_once('car.php');require_once('mobile.php');$car = new Car();$mobile = new Mobile();$car->gps();echo "\n";$mobile->gps();

输出结果如下:

1 i can gps2 i can gps

例子2

在 car 中引入了另外一个国产的 gps 。

gpschina.php 定义如下:

<?phptrait GpsChina {    public function gps() {        echo 'i can chinae gps';    }}

在 car 中引入,修改 car.php 的定义如下:

<?phpclass Car {    use gps, gpschina;        public function move() {        echo 'i can move';    }}

再次调用 test.php 进行测试,这时会报错,报错如下:

(本文来)源gaodaimacom搞#^代%!码&网(

搞gaodaima代码

1 Fatal error: Trait method gps has not been applied, because there are collisions with other trait methods on Car in Car.php on line 4

因为在引入的 trait 中 gps 和 gpschina 各有一个 gps ,而直接使用 $car->gps() 时无法确定到底使用的是 gps 的 gps() 方法,还是使用的 gpschina 的 gps() 方法,因此报错了。这样的话,我们需要确定一个。修改 car.php 文件。

<?phpclass Car {    use gps, gpschina {        GpsChina::gps insteadof Gps;    }        public function move() {        echo 'i can move';    }}

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:php中trait是什么?php中trait的简单介绍

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址