您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
php多个trait方法冲突-别名as
发布时间:2021-09-24 16:09:07编辑:雪饮阅读()
像是上文中php中trait多个方法重名后可以使用insteadof进行替换以实现指定到底从多个方法中走那个trait的方法。那么在insteadof后还可以通过as实现某个trait的某个方法的别名。
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";
}
}
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;
Dog2::walk as walk2;
}
}
$cat = new Cat();
$cat->say();
$cat->walk();
$cat->say2();
$cat->walk2();
?>
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";
}
}
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;
Dog2::walk as walk2;
}
}
$cat = new Cat();
$cat->say();
$cat->walk();
$cat->say2();
$cat->walk2();
?>
运行结果:
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 dog2 walk
关键字词:php,trait,as,别名