0%

PHP Traits

Trait

Traits are 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.

Trait 是一种代码重用的机制,由于PHP语言本身并不像C++等语言一样支持类的多继承,PHP用trait来实现“多继承”。用户可以用Trait声明一个包含属性和方法的对象,类可以引入多个trait并继承其中的属性和方法,以此来实现多继承

Note

  • trait 对象不能实例化

Usage

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php

trait t
{
public function helloWorld()
{
printf("Hello World\n");
}
}

class c
{
use t;
}

$c = new c;
$c->helloWorld();
?>

输出

1
2
$ php helloWorld.php 
Hello World

用trait实现多继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php

trait t1
{
public function helloWorld()
{
printf("Hello World\n");
}
}

trait t2
{
public function thankYou()
{
print("Thank you\n");
}
}

class c
{
use t1, t2;
}

$c = new c;
$c->helloWorld();
$c->thankYou();
?>

输出

1
2
3
$ php c.php
Hello World
Thank you

Precedence

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.

子类的属性和方法 > trait的属性和方法 > 父类的属性和方法

Reference & Thanks