PHP 代码复用机制 trait
2023-09-11 14:18:27 时间
- 1. trait 的介绍
- 2. trait 的基础用法
- 3. trait 的优先级
- 4. trait 的 as 用法
- 5. 引入多个 trait 时的成员同名问题
1. trait 的介绍
众所周知,PHP 是单继承的语言,也就是 PHP 中的类只能继承一个父类,无法同时从多个基类中继承属性和方法,于是 PHP 实现了一种代码复用的方法,称之为 trait,使开发人员可以在不同层次结构内独立的类中复用属性和方法
trait 不是接口也不是类,不可以被实例化也不可以被继承,只是用来将公共代码(属性和方法)提供给其他类使用的
2. trait 的基础用法
trait 的成员:trait 的成员只能有属性和方法,不能定义类常量
// 定义一个 trait
trait Say
{
// 在 trait 中不能定义常量
// 报错提示:Traits cannot h**e constants
// const PI = 3.14; // 错误示例
// 属性
public static $name = 'liang';
// 方法
public static function hello()
{
echo 'Hello World !';
}
}
class User
{
use Say; // 在类中引入 trait
}
// 测试输出
echo User::$name;
echo User::hello();
3. trait 的优先级
类成员和 trait 成员同名,属性和方法有不同的处理
如果是属性同名,PHP 直接抛出致命错误,方法同名则会有优先级之分
优先顺序是来自当前类的成员覆盖了 trait 的方法,而 trait 则覆盖了被继承的方法
当前类成员 > trait 成员 > 继承的成员
4. trait 的 as 用法
trait User
{
protected function hello()
{
echo 'user hello';
}
}
class Person
{
use User {
# 起别名
hello as helloNewName;
# 起别名并且修改方法的访问控制
hello as public helloNewName;
}
}
$o = new Person;
$o->helloNewName(); // user hello
5. 引入多个 trait 时的成员同名问题
引入多个 trait 时,如果存在成员同名,那么 PHP 会直接抛出致命错误
为了解决多个 trait 在同一个类中的命名冲突,需要使用 insteadof 操作符来明确指定使用冲突方法中的哪一个
也就是需要使用 insteadof 操作符指定使用哪个 trait 中的成员
trait User
{
public function hello()
{
echo 'user hello <br>';
}
}
trait Admin
{
public function hello()
{
echo 'admin hello <br>';
}
}
class Person
{
use User, Admin {
// 指定 hello 方法应用哪个 trait 上的
Admin::hello insteadof User;
// User 上的 hello 想要使用的话就定义个别名,不想使用可以不定义别名
User::hello as helloUser;
}
}
$o = new Person;
$o->hello();
$o->helloUser();
相关文章
- 全面解读php-运算符
- 利用 Composer 一步一步构建自己的 PHP 框架(一)——基础准备
- php之快速入门学习-13(PHP 循环 - While 循环)
- 渗透测试-文件上传之获取php信息(一)
- php go使用clickhouse
- nginx配置后只有根目录首页index.php能访问,其他页面404
- 《PHP和MySQL Web开发从新手到高手(第5版)》一1.5 向虚拟主机询问什么
- 《PHP、MySQL和Apache入门经典(第5版)》一2.3 在Linux/UNIX上安装MySQL
- php中GD库的简单使用
- [xDebug]Xdebug和Sublime调试PHP代码
- 转 php中$_request与$_post、$_get的区别
- php base64不能解码_PHP base64编码后解码乱码的解决办法
- PHP防XSS 防SQL注入的代码
- php面试题之三——PHP语言基础(基础部分)
- php面向对象高级-魔术方法与迭代器
- linux下无法执行PHP命令,错误 php: command not found
- Netbeans+CodeIgniter搭建PHP开发环境
- DokuWiki 开源框架 PHP DokuWiki
- 一个CMS案例实战讲解PHP代码审计入门
- php源码安全加密之PHP混淆算法.