1<?php
2/**
3 * Inheritance in unnecessary function is also called we we don't require them, so we can prevent them using traits
4 * Trait is only available when we use them otherwise not!
5 */
6trait A
7{
8 function fun1()
9 {
10 echo "class A called";
11 }
12}
13class B
14{
15 use A;
16 function fun2()
17 {
18 echo "class B called";
19 }
20}
21class C extends B
22{
23 function fun3()
24 {
25 echo "class C called";
26 }
27}
28class D extends C
29{
30 use A;
31 function fun4()
32 {
33 echo "class D called";
34 }
35}
36$obj = new C();
37$obj->fun1();
38?>
1
2<?php
3trait Hello {
4 public function sayHello() {
5 echo 'Hello ';
6 }
7}
8
9trait World {
10 public function sayWorld() {
11 echo 'World!';
12 }
13}
14
15trait HelloWorld {
16 use Hello, World;
17}
18
19class MyHelloWorld {
20 use HelloWorld;
21}
22
23$o = new MyHelloWorld();
24$o->sayHello();
25$o->sayWorld();
26?>
27
28 // L'exemple ci-dessus va afficher : Hello World !
29
1
2<?php
3class Base {
4 public function sayHello() {
5 echo 'Hello ';
6 }
7}
8
9trait SayWorld {
10 public function sayHello() {
11 parent::sayHello();
12 echo 'World!';
13 }
14}
15
16class MyHelloWorld extends Base {
17 use SayWorld;
18}
19
20$o = new MyHelloWorld();
21$o->sayHello();
22?>
23
24