您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
php的trait嵌套
发布时间:2021-09-24 20:50:06编辑:雪饮阅读()
上篇中了解了php中trait的as修改控制访问与别名(同时)。
那么这里接触一个新的知识点,就说这个trait还支持嵌套,也就是说trait中use另外一个trait。
test.php:
<?php
trait Cat{
public function eat(){
echo "This is Cat eat";
}
}
trait Dog{
use Cat;
public function drive(){
echo "This is Dog drive";
}
}
class animal{
use Dog;
public function getName(){
echo "This is animal name";
}
}
$animal = new animal();
$animal->eat();
?>
trait Cat{
public function eat(){
echo "This is Cat eat";
}
}
trait Dog{
use Cat;
public function drive(){
echo "This is Dog drive";
}
}
class animal{
use Dog;
public function getName(){
echo "This is animal name";
}
}
$animal = new animal();
$animal->eat();
?>
运行结果:
C:\Users\Administrator\PhpstormProjects\untitled\organizing>D:\phpstudy_pro\Extensions\php\php7.3.4nts\php.exe C:\Users\Administrator\PhpstormProjects\untitled\test.php
This is Cat eat
这里是animal中调用eat,然后寻址就是animal=>Dog=>Cat=>eat。
关键字词:php,trait