Traits method overriding
<?php
//Here below, we have called same method from Trait, parent Class as well as Child Class.We have
//called "sayhello" method using Child Class Object. So here First Priority will be given to the Child
//Class(if method present in the Child class)then Second Priority will be given to the trait
//(if method present in the trait) and then Third Priority will be given to the Parent Class
//(if method present in the parent Class).
// EXAMPLE 1 :
// trait hello
// {
// public function sayhello()
// {
// echo "Hello from trait" . "<br>";
// }
// }
// class Base
// {
// public function sayhello()
// {
// echo "Hello from Base Class" . "<br>";
// }
// }
// class Child extends Base
// {
// use hello;
// public function sayhello()
// {
// echo "Hello from Child Class" . "<br>";
// }
// }
// $test = new Child();
// $test->sayhello();
// EXAMPLE 2:
//If We have multiple traits with the same method name and if we want to call any specific method from
//any specific trait then we can follow below steps:
//In the Base class we can specify all the traits after that we can specifity syntax as below:
//trait_name::function_name insteadOf another_trait_name;
//And also we can call another function from another traits by Renaming those Function as shown below:
// trait hello
// {
// public function sayhello()
// {
// echo "Hello from Hello trait" . "<br>";
// }
// }
// trait hi
// {
// public function sayhello()
// {
// echo "Hello from Hi trait" . "<br>";
// }
// }
// class Base
// {
// use hello, hi {
// hello::sayhello insteadOf hi;
// hi::sayhello as newhello; //We can Rename the function from sayhello to newhello
// }
// }
// $test = new Base();
// $test->sayhello();
// $test->newhello();
// EXAMPLE 3:
//We can't access private method directly. So to use privated method(from trait) in Class as can make
//privated method to public as shown below:
trait hello
{
private function sayhello()
{
echo "Hello from Hello trait" . "<br>";
}
}
class Base
{
use hello {
//Making private method to public and we can Rename to method as shown below:
hello::sayhello as public newhello;
}
}
$test = new Base();
$test->newhellow();
?>
Comments
Post a Comment