Bird
Raised Fist0
PHPprogramming~20 mins

Trait declaration and usage in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Trait Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of trait method usage
What is the output of this PHP code using a trait?
PHP
<?php
trait Hello {
    public function sayHello() {
        return "Hello from trait!";
    }
}

class Greeter {
    use Hello;
}

$g = new Greeter();
echo $g->sayHello();
?>
AFatal error: Trait method sayHello not found
BParse error: syntax error, unexpected 'use'
CHello from class Greeter!
DHello from trait!
Attempts:
2 left
💡 Hint
Traits allow classes to reuse methods defined inside them.
❓ Predict Output
intermediate
2:00remaining
Trait method conflict resolution
What will be the output of this PHP code with two traits having the same method name?
PHP
<?php
trait A {
    public function message() {
        return "Message from A";
    }
}

trait B {
    public function message() {
        return "Message from B";
    }
}

class Test {
    use A, B {
        B::message insteadof A;
    }
}

$obj = new Test();
echo $obj->message();
?>
AMessage from B
BMessage from A
CFatal error: Trait method message has not been applied
DParse error: syntax error, unexpected 'insteadof'
Attempts:
2 left
💡 Hint
The insteadof keyword resolves method conflicts by choosing one trait's method.
🔧 Debug
advanced
2:00remaining
Identify the error in trait usage
What error will this PHP code produce?
PHP
<?php
trait Logger {
    public function log($msg) {
        echo $msg;
    }
}

class Service {
    use Logger
    public function run() {
        $this->log("Running service\n");
    }
}

$s = new Service();
$s->run();
?>
AOutput: Running service
BFatal error: Trait Logger not found
CParse error: syntax error, unexpected 'public' (missing semicolon after use statement)
DWarning: Undefined method log
Attempts:
2 left
💡 Hint
Check punctuation after the use statement inside the class.
🧠 Conceptual
advanced
2:00remaining
Trait properties and visibility
Consider this PHP code using a trait with a property. What will be the output?
PHP
<?php
trait Counter {
    private int $count = 0;
    public function increment() {
        $this->count++;
    }
    public function getCount() {
        return $this->count;
    }
}

class Clicker {
    use Counter;
}

$c = new Clicker();
$c->increment();
$c->increment();
echo $c->getCount();
?>
AFatal error: Cannot access private property
B2
C0
DParse error: syntax error
Attempts:
2 left
💡 Hint
Traits can have properties with visibility, and the class uses them as if declared inside it.
🚀 Application
expert
3:00remaining
Using multiple traits with method aliasing
Given this PHP code, what is the output?
PHP
<?php
trait T1 {
    public function greet() {
        return "Hello from T1";
    }
}

trait T2 {
    public function greet() {
        return "Hello from T2";
    }
}

class MyClass {
    use T1, T2 {
        T1::greet as greetT1;
        T2::greet insteadof T1;
    }
    public function greet() {
        return $this->greetT1() . " and " . T2::greet();
    }
}

$obj = new MyClass();
echo $obj->greet();
?>
AFatal error: Cannot call trait method statically
BHello from T2 and Hello from T1
CParse error: syntax error
DHello from T1 and Hello from T2
Attempts:
2 left
💡 Hint
Check how trait methods are called inside the class method.

Practice

(1/5)
1. What is the main purpose of a trait in PHP?
easy
A. To reuse code in multiple classes without using inheritance
B. To define a new class type
C. To create a database connection
D. To handle exceptions in code

Solution

  1. Step 1: Understand what traits are

    Traits are a way to reuse code in multiple classes without inheritance.
  2. Step 2: Compare options with trait purpose

    Only To reuse code in multiple classes without using inheritance correctly describes traits as a code reuse tool without inheritance.
  3. Final Answer:

    To reuse code in multiple classes without using inheritance -> Option A
  4. Quick Check:

    Traits = Code reuse without inheritance [OK]
Hint: Traits are for code reuse without inheritance [OK]
Common Mistakes:
  • Confusing traits with classes
  • Thinking traits handle exceptions
  • Assuming traits create database connections
2. Which of the following is the correct syntax to declare a trait named Logger in PHP?
easy
A. interface Logger { public function log(); }
B. class Logger { public function log() { echo 'Log message'; } }
C. trait Logger { public function log() { echo 'Log message'; } }
D. function Logger() { echo 'Log message'; }

Solution

  1. Step 1: Identify trait declaration syntax

    Traits are declared using the keyword trait followed by the trait name and curly braces.
  2. Step 2: Match options with correct syntax

    trait Logger { public function log() { echo 'Log message'; } } uses trait Logger { ... } which is correct. Others declare class, interface, or function incorrectly.
  3. Final Answer:

    trait Logger { public function log() { echo 'Log message'; } } -> Option C
  4. Quick Check:

    Trait declaration = trait keyword + name [OK]
Hint: Use 'trait' keyword to declare traits [OK]
Common Mistakes:
  • Using 'class' instead of 'trait'
  • Confusing traits with interfaces
  • Declaring traits as functions
3. What will be the output of the following PHP code?
trait Hello {
    public function sayHello() {
        echo 'Hello';
    }
}

class Greet {
    use Hello;
}

$obj = new Greet();
$obj->sayHello();
medium
A. HelloHello
B. Fatal error: Method sayHello not found
C. No output
D. Hello

Solution

  1. Step 1: Understand trait usage in class

    The class Greet uses the trait Hello, so it inherits the sayHello method.
  2. Step 2: Check method call output

    Calling $obj->sayHello() will execute the trait method, printing 'Hello'.
  3. Final Answer:

    Hello -> Option D
  4. Quick Check:

    Trait method call = 'Hello' output [OK]
Hint: Trait methods become class methods when used [OK]
Common Mistakes:
  • Expecting error because trait is not a class
  • Thinking method is not available
  • Assuming method prints twice
4. Identify the error in the following PHP code using traits:
trait Logger {
    public function log() {
        echo 'Logging';
    }
}

class User {
    use Logger
    public function create() {
        echo 'User created';
    }
}
medium
A. Class cannot use traits
B. Missing semicolon after use Logger
C. Trait cannot have public methods
D. Method create must be static

Solution

  1. Step 1: Check trait usage syntax

    When using a trait inside a class, the use statement must end with a semicolon.
  2. Step 2: Identify missing semicolon

    The code misses a semicolon after use Logger, causing a syntax error.
  3. Final Answer:

    Missing semicolon after use Logger -> Option B
  4. Quick Check:

    Trait use requires semicolon [OK]
Hint: Add semicolon after trait use in class [OK]
Common Mistakes:
  • Omitting semicolon after trait use
  • Thinking traits can't have public methods
  • Assuming methods must be static
5. Given two traits TraitA and TraitB both defining a method greet(), how can a class Welcome use both traits and specify that TraitB::greet() should be used instead of TraitA::greet()?
trait TraitA {
    public function greet() {
        echo 'Hello from A';
    }
}

trait TraitB {
    public function greet() {
        echo 'Hello from B';
    }
}

class Welcome {
    use TraitA, TraitB {
        TraitB::greet insteadof TraitA;
    }
}
hard
A. The code correctly uses insteadof to prefer TraitB's greet method
B. You cannot use two traits with same method names in one class
C. Use as keyword instead of insteadof
D. Rename one trait method to avoid conflict

Solution

  1. Step 1: Understand trait conflict resolution

    When two traits have methods with the same name, PHP requires explicit conflict resolution using insteadof.
  2. Step 2: Check the code's conflict resolution

    The code uses TraitB::greet insteadof TraitA; which correctly tells PHP to use TraitB's method.
  3. Final Answer:

    The code correctly uses insteadof to prefer TraitB's greet method -> Option A
  4. Quick Check:

    Use 'insteadof' to resolve trait method conflicts [OK]
Hint: Use 'insteadof' to choose trait method on conflict [OK]
Common Mistakes:
  • Ignoring method conflicts in traits
  • Using 'as' instead of 'insteadof' for conflicts
  • Thinking traits with same method names can't be used
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard