0
0
PHPprogramming~10 mins

Why traits are needed in PHP - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to use a trait in a class.

PHP
<?php
trait Logger {
    public function log($msg) {
        echo $msg;
    }
}

class User {
    use [1];
}

$user = new User();
$user->log('Hello');
?>
Drag options to blanks, or click blank then click option'
ATraitLogger
BLog
CLogger
DLogging
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong trait name that does not exist.
Forgetting to use the use keyword inside the class.
2fill in blank
medium

Complete the code to fix the error when two traits have the same method name.

PHP
<?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();
?>
Drag options to blanks, or click blank then click option'
AA
BB
CMyClass
Dhello
Attempts:
3 left
💡 Hint
Common Mistakes
Not resolving method name conflicts causes fatal errors.
Swapping the order of traits in the conflict resolution.
3fill in blank
hard

Fix the error in the code by completing the blank to call the trait method inside the class method.

PHP
<?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();
?>
Drag options to blanks, or click blank then click option'
AHelloWorld
Bself
Cparent
D$this
Attempts:
3 left
💡 Hint
Common Mistakes
Using parent or self instead of the trait name.
Trying to call the method on $this which causes recursion.
4fill in blank
hard

Fill both blanks to create a trait with a method and use it in a class.

PHP
<?php
trait [1] {
    public function greet() {
        echo 'Hi!';
    }
}

class Person {
    use [2];
}

$p = new Person();
$p->greet();
?>
Drag options to blanks, or click blank then click option'
AGreeter
BPerson
CGreeterTrait
DGreet
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the trait declaration and usage.
Confusing class names with trait names.
5fill in blank
hard

Fill all three blanks to define a trait, use it in a class, and call its method.

PHP
<?php
trait [1] {
    public function sayHi() {
        echo 'Hi there!';
    }
}

class [2] {
    use [3];
}

$obj = new [2]();
$obj->sayHi();
?>
Drag options to blanks, or click blank then click option'
AFriendly
BGreeter
DUser
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up trait and class names.
Using different trait names in declaration and usage.