PHP之高级特性trait

php从以前到现在一直都是单继承的语言,无法同时从两个基类中继承属性和方法,为了解决这个问题,php出了Trait这个特性。
Trait 是为类似 PHP 的单继承语言而准备的一种代码复用机制。Trait 为了减少单继承语言的限制,使开发人员能够自由地在不同层次结构内独立的类中复用 method。Trait 和 Class 组合的语义定义了一种减少复杂性的方式,避免传统多继承和 Mixin 类相关典型问题。

<?php
/**
 * trait 基本用法
 */
trait R {
    function rich () {
		//...
	}
}
class HH {
	use R;
	function handsome() {
    //...
}
}

$obj = new HH();
$obj->rich();

<?php
trait firstTrait {
	function firstMethod() { echo "method1"; }
}
  
trait secondTrait {
	// trait 中也可以用抽象方法
    abstract function secondMethod();
}

class firstClass {
    // 使用多个 trait:
    use firstTrait, secondTrait;

	function secondMethod() {
		//...
	}
}
  
$obj = new firstClass();
  
// Valid
$obj->firstMethod(); // Print : method1
  
// Valid
$obj->secondMethod(); // Print : method2

<?php

trait firstTrait {
	function firstMethod() { echo "method1"; }
}
trait secondTrait {
	// trait 中使用 trait:
    use firstTrait;
    function secondMethod() { echo "method2"; }
}
class firstClass {
    use secondTrait;
}
  
$obj= new firstClass();
// Valid
$obj->firstMethod(); // Print : method1
// Valid
$obj->secondMethod(); // Print : method2

<?php
trait firstTrait {
	function sameMethodName() { echo "method in firstTrait\n"; }
}
  
trait secondTrait {
    function sameMethodName() { echo "method in secontTrait\n"; }
}

class firstClass {
    // 使用firstTrait中的sameMethodName()方法而不是用secondTrait中的。:
    use firstTrait, secondTrait {
		firstTrait::sameMethodName insteadof secondTrait;
	}
}
  
$obj = new firstClass();
  
$obj->sameMethodName(); // Print : method in firstTrait
  

<?php
trait firstTrait {
	function sameMethodName() { echo "method in firstTrait\n"; }
}
  
trait secondTrait {
    function sameMethodName() { echo "method in secontTrait\n"; }
}

class firstClass {
    use firstTrait, secondTrait {
		// 使用firstTrait中的sameMethodName()方法而不是用secondTrait中的。:
		firstTrait::sameMethodName insteadof secondTrait;
		// 使用secondTrait中的sameMethoName()方法但改名为 anotherMethodName():
		secondTrait::sameMethodName as public anotherMethodName;
	}
}
  
$obj = new firstClass();
$obj->sameMethodName(); 
$obj->anotherMethodName();
  

特性详细介绍:http://php.net/traits

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值