php的trait用在非继承类及as修改方法的访问控制
发布时间:2021-09-24 17:56:34编辑:雪饮阅读()
前面有说过trait用在继承中的派生类上,实际上那样只是为了实例一个使用场景。
那么说其实也可以用在非继承的普通类上面。
test.php:
<?php
trait Animal{
public function eat(){
echo "This is Animal eat";
}
}
class Dog{
use Animal;
}
$dog = new Dog();
//报错,因为已经把eat改成了保护
$dog->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 Animal eat
另外一个就是前面有了解过as进行别名,那么as除了别名,还可以修改trait中方法的访问控制权限于使用trait的类中。
test.php:
<?php
trait Animal{
public function eat(){
echo "This is Animal eat";
}
}
class Dog{
use Animal{
eat as protected;
}
}
$dog = new Dog();
//报错,因为已经把eat改成了保护
$dog->eat();
?>
运行结果自然是报错了:
C:\Users\Administrator\PhpstormProjects\untitled\organizing>D:\phpstudy_pro\Extensions\php\php7.3.4nts\php.exe C:\Users\Administrator\PhpstormProjects\untitled\test.php
Fatal error: Uncaught Error: Call to protected method Dog::eat() from context '' in C:\Users\Administrator\PhpstormProjects\untitled\test.php on line 15
Error: Call to protected method Dog::eat() from context '' in C:\Users\Administrator\PhpstormProjects\untitled\test.php on line 15
Call Stack:
0.0002 395024 1. {main}() C:\Users\Administrator\PhpstormProjects\untitled\test.php:0
那么我也可以修改成public,这样和这里对应trait中原来方法的访问控制一样了:
test.php:
<?php
trait Animal{
public function eat(){
echo "This is Animal eat";
}
}
class Dog{
use Animal{
eat as public;
}
}
$dog = new Dog();
$dog->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 Animal eat