Traits
Traits reduce some limitations of single inheritance. In essence, traits are similar to abstract classes and can contain any number of properties and methods. A class can then
use
any number of traits, e.g.
trait Hello
{
function sayHello() {
return "Hello";
}
}
trait World
{
function sayWorld() {
return "World";
}
}
class MyWorld
{
use Hello, World;
}
$world = new MyWorld();
echo $world->sayHello() . ' ' . $world->sayWorld();
An inherited method from a base class is overridden by the method inserted into MyHelloWorld from the SayWorld Trait. The behavior is the same for methods defined in the MyHelloWorld class. The precedence order is that methods from the current class override Trait methods, which in turn override methods from the base class.
<?phpclass Base {
public function sayHello() {
echo 'Hello ';
}
}
trait SayWorld {
public function sayHello() {
parent::sayHello();
echo 'World!';
}
}
class MyHelloWorld extends Base {
use SayWorld;
}
$o = new MyHelloWorld();$o->sayHello();?>
The above example will output:
Hello World!
0 comments:
Post a Comment