Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
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.
✗ Incorrect
The trait is declared with the keyword trait followed by its name. Here, the correct name is Logger.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong trait name in the use statement.
Forgetting the semicolon after the use statement.
✗ Incorrect
The use keyword inside a class includes the trait. The trait name is Logger.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Writing 'uses' or 'using' instead of 'use'.
Trying to include traits like files with 'include'.
✗ Incorrect
The correct keyword to include a trait inside a class is use.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'class' instead of 'trait' to declare a trait.
Using 'extends' instead of 'use' to include a trait.
✗ Incorrect
The trait is declared with trait and included in the class with use.
5fill in blank
hardFill 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'
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.
✗ Incorrect
The trait is declared with trait, included in the class with use, and the method log is called.