Complete the code to use a trait in a class.
<?php
trait Logger {
public function log($msg) {
echo $msg;
}
}
class User {
use [1];
}
$user = new User();
$user->log('Hello');
?>use keyword inside the class.The use keyword includes the trait named Logger inside the class.
Complete the code to fix the error when two traits have the same method name.
<?php
trait A {
public function hello() {
echo 'Hello from A';
}
}
trait B {
public function hello() {
echo 'Hello from B';
}
}
class MyClass {
use A, B {
[1]::hello insteadof [2];
}
}
$obj = new MyClass();
$obj->hello();
?>When two traits have the same method, you must specify which one to use with insteadof. Here, A::hello insteadof B means use hello from trait A.
Fix the error in the code by completing the blank to call the trait method inside the class method.
<?php
trait HelloWorld {
public function sayHello() {
echo 'Hello World';
}
}
class MyClass {
use HelloWorld;
public function sayHello() {
[1]::sayHello();
echo ' from MyClass';
}
}
$obj = new MyClass();
$obj->sayHello();
?>parent or self instead of the trait name.$this which causes recursion.To call the trait method inside the class method, use the trait name followed by :: and the method name.
Fill both blanks to create a trait with a method and use it in a class.
<?php trait [1] { public function greet() { echo 'Hi!'; } } class Person { use [2]; } $p = new Person(); $p->greet(); ?>
The trait name must be the same where it is declared and used. Here, Greeter is used in both places.
Fill all three blanks to define a trait, use it in a class, and call its method.
<?php trait [1] { public function sayHi() { echo 'Hi there!'; } } class [2] { use [3]; } $obj = new [2](); $obj->sayHi(); ?>
The trait is named Friendly, the class is User, and the class uses the trait Friendly.