Bird
0
0

What will be the output of the following PHP code?

medium📝 Predict Output Q4 of 15
PHP - Interfaces and Traits
What will be the output of the following PHP code?
trait Logger {
    public function log() {
        return 'Logging';
    }
}

class User {
    use Logger;
}

$user = new User();
echo $user->log();
AFatal error: Trait not found
BCall to undefined method User::log()
CLogging
DNo output
Step-by-Step Solution
Solution:
  1. Step 1: Understand trait usage in class

    The trait Logger defines a method log(). The class User uses this trait, so User has the log() method.
  2. Step 2: Check the output of calling log()

    Calling $user->log() returns 'Logging', so echo prints 'Logging'.
  3. Final Answer:

    Logging -> Option C
  4. Quick Check:

    Trait method available in class = Logging [OK]
Quick Trick: Traits add methods to classes directly [OK]
Common Mistakes:
  • Assuming traits need instantiation
  • Expecting errors for trait usage
  • Forgetting to use the trait in the class

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes