您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
php多个trait时候的多个别名as情况下的简写
发布时间:2021-09-24 17:14:36编辑:雪饮阅读()
上篇中了解了单个trait别名时候是可以简写的,但是实际上以我个人理解,这个不在乎于是否单个trait,而在乎于对于方法的寻址,就算是有多个trait,多个方法,只要这个方法能够寻址(唯一路径)。那么也可以在同时use多个trait的时候实现as的简写于方法。
test.php:
<?php
declare(strict_types=1);
trait Dog{
public function say(){
echo "This is dog say";
}
public function walk(){
echo "This is dog walk";
}
}
trait Dog2{
public function say(){
echo "This is dog2 say";
}
public function walk(){
echo "This is dog2 walk";
}
public function mad(){
echo "This is dog2 mad";
}
}
class Animal{
public function eat(){
echo "This is animal eat";
}
}
class Cat extends Animal{
use Dog,Dog2{
Dog2::say insteadof Dog;
Dog2::walk insteadof Dog;
Dog2::say as say2;
mad as mad2;
walk as walk2;
}
}
$cat = new Cat();
$cat->say();
$cat->walk();
$cat->say2();
$cat->walk2();
$cat->mad2();
?>
declare(strict_types=1);
trait Dog{
public function say(){
echo "This is dog say";
}
public function walk(){
echo "This is dog walk";
}
}
trait Dog2{
public function say(){
echo "This is dog2 say";
}
public function walk(){
echo "This is dog2 walk";
}
public function mad(){
echo "This is dog2 mad";
}
}
class Animal{
public function eat(){
echo "This is animal eat";
}
}
class Cat extends Animal{
use Dog,Dog2{
Dog2::say insteadof Dog;
Dog2::walk insteadof Dog;
Dog2::say as say2;
mad as mad2;
walk as walk2;
}
}
$cat = new Cat();
$cat->say();
$cat->walk();
$cat->say2();
$cat->walk2();
$cat->mad2();
?>
像是这里mad别名为mad2,可以不用声明前缀,是因为mad只在Dog2类下有,也就保证了唯一寻址。
而walk别名为walk2同样也不用声明前缀,是因为Dog的walk已经替换为Dog2的walk了,所以寻址也是唯一的。
那么运行结果如:
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 dog2 sayThis is dog2 walkThis is dog2 sayThis is dog walkThis is dog2 mad
关键字词:php,trait