0
0
PHPprogramming~10 mins

Trait declaration and usage in PHP - Interactive Code Practice

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

Complete the code to declare a trait named Logger.

PHP
<?php
trait [1] {
    public function log($msg) {
        echo $msg;
    }
}
?>
Drag options to blanks, or click blank then click option'
ATraitLogger
BLogTrait
CLoggerTrait
DLogger
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'class' instead of 'trait' to declare a trait.
Using a different trait name than the one used later.
2fill in blank
medium

Complete the code to use the trait Logger inside the class Application.

PHP
<?php
class Application {
    use [1];
}
?>
Drag options to blanks, or click blank then click option'
ALogTrait
BLogger
CApplicationTrait
DTraitLogger
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong trait name in the use statement.
Forgetting the semicolon after the use statement.
3fill in blank
hard

Fix the error in the code by completing the trait usage syntax.

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

class App {
    [1] Logger;
}
?>
Drag options to blanks, or click blank then click option'
Ausing
Buses
Cuse
Dinclude
Attempts:
3 left
💡 Hint
Common Mistakes
Writing 'uses' or 'using' instead of 'use'.
Trying to include traits like files with 'include'.
4fill in blank
hard

Fill both blanks to declare a trait and use it inside a class.

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

class System {
    [2] Logger;
}
?>
Drag options to blanks, or click blank then click option'
Atrait
Bclass
Cuse
Dextends
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'class' instead of 'trait' to declare a trait.
Using 'extends' instead of 'use' to include a trait.
5fill in blank
hard

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

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

class App {
    [2] Logger;

    public function run() {
        $this->[3]("Hello from trait!\n");
    }
}

$app = new App();
$app->run();
?>
Drag options to blanks, or click blank then click option'
Atrait
Blog
Cuse
Drun
Attempts:
3 left
💡 Hint
Common Mistakes
Calling a method name that does not exist in the trait.
Forgetting to include the trait with 'use' inside the class.