1.trait 是为单继承语言量身定制的代码复用机制
2.trait 简单理解为一个方法集合
3.trait可以看做是一个特殊的类,但不嫩被实例化,仅允许被类调用
实例
<?php header("content-type:text/html;charset=utf-8"); class Person { protected $name; public function __construct($name='test') { $this->name=$name; } public function study($course='progamming') { return $this->name.' is studing'.$course; } } trait Course { public $friend='john'; public function sport($name='mysql') { $this->name.$this->friend.' is studing'.$name; } abstract public static function hobby($name); public function study($course ='html') { return $this->name.'is studing'.$course; } } class Student extends Person { use Course; protected $name='test1'; public static function hobby($name) { return $name; } public function study($course='java') { return $this->name.' is studing '.$course; } } $student = new Student(); echo $student->study();
运行实例 »
点击 "运行实例" 按钮查看在线实例