PHP insteadof 关键字
实例
使用 insteadof
从不同的特征中选择方法:
<?php
trait message1 {
public function msgA() {
echo "My favorite color is red. ";
}
public function msgB() {
echo "My favorite number is 5. ";
}
}
trait message2 {
public function msgA() {
echo "My favorite color is blue. ";
}
public function msgB() {
echo "My favorite number is 7. ";
}
}
class MyClass {
use message1, message2 {
message1::msgA insteadof message2;
message2::msgB insteadof message1;
}
}
$obj = new MyClass();
$obj->msgA();
$obj->msgB();
?>
亲自试一试 »
trait message1 {
public function msgA() {
echo "My favorite color is red. ";
}
public function msgB() {
echo "My favorite number is 5. ";
}
}
trait message2 {
public function msgA() {
echo "My favorite color is blue. ";
}
public function msgB() {
echo "My favorite number is 7. ";
}
}
class MyClass {
use message1, message2 {
message1::msgA insteadof message2;
message2::msgB insteadof message1;
}
}
$obj = new MyClass();
$obj->msgA();
$obj->msgB();
?>
定义和用法
insteadof
关键字允许您在多个 trait 具有同名方法时选择应该从哪个 trait 中获取方法。
相关页面
trait
关键字
在我们的 PHP OOP - Traits 教程中了解更多关于 Traiy 的信息。