traits
triat has single inheritance
it will show error because a function repeated in two traits
<!DOCTYPE html>
<html>
<body>
<?php
trait message1 {
public function msg1() {
echo "OOP is fun! ";
}
public function msg2() {
echo "OOsssP reduces code duplication!";
}
}
trait message2 {
public function msg2() {
echo "OOP reduces code duplication!";
}
}
class Welcome {
use message1;
}
class Welcome2 {
use message1, message2;
}
$obj = new Welcome();
$obj->msg1();
echo "<br>";
$obj2 = new Welcome2();
$obj2->msg1();
$obj2->msg2();
?>
</body>
</html>
no two traits same function if we import
error fateal error:
The error will occur in this part of the code:
$obj2 = new Welcome2(); $obj2->msg1(); $obj2->msg2(); // This line will cause an error
php$obj2 = new Welcome2();
$obj2->msg1();
$obj2->msg2(); // This line will cause an error
The error message you might encounter is something like:
Fatal error: Trait method msg2 has not been applied, because there are collisions with the method in class Welcome2
sqlFatal error: Trait method msg2 has not been applied, because there are collisions with the method in class Welcome2
working code
<!DOCTYPE html>
<html>
<body>
<?php
trait message1 {
public function msg1() {
echo "OOP is fun! ";
}
}
trait message2 {
public function msg2() {
echo "OOP reduces code duplication!";
}
}
class Welcome {
use message1;
}
class Welcome2 {
use message1, message2;
}
$obj = new Welcome();
$obj->msg1();
echo "<br>";
$obj2 = new Welcome2();
$obj2->msg1();
$obj2->msg2();
?>
</body>
</html>
s
No comments:
Post a Comment