Bird
0
0

Which of the following code snippets correctly implements this?

hard📝 Application Q8 of 15
PHP - Inheritance and Polymorphism
You want to create an abstract class Logger with an abstract method log() that accepts a string message. Then create a subclass FileLogger that writes the message to a file. Which of the following code snippets correctly implements this?
Aabstract class Logger { public function log(string $msg) {} } class FileLogger extends Logger { public function log(string $msg) { file_put_contents('log.txt', $msg.PHP_EOL); } }
Babstract class Logger { abstract public function log(string $msg); } class FileLogger extends Logger { public function log(string $msg) { file_put_contents('log.txt', $msg.PHP_EOL, FILE_APPEND); } }
Cclass Logger { abstract public function log(string $msg); } class FileLogger extends Logger { public function log(string $msg) { file_put_contents('log.txt', $msg.PHP_EOL, FILE_APPEND); } }
Dabstract class Logger { abstract public function log(); } class FileLogger extends Logger { public function log(string $msg) { file_put_contents('log.txt', $msg.PHP_EOL, FILE_APPEND); } }
Step-by-Step Solution
Solution:
  1. Step 1: Check abstract class and method declaration

    Logger is abstract and declares abstract method log() with string parameter.
  2. Step 2: Check subclass implementation

    FileLogger extends Logger and implements log(string $msg) correctly, appending message to file.
  3. Step 3: Verify file_put_contents usage

    Uses FILE_APPEND flag to add message without overwriting file.
  4. Final Answer:

    abstract class Logger with abstract log(string $msg) implemented correctly in FileLogger. -> Option B
  5. Quick Check:

    Abstract method with parameter and correct subclass implementation [OK]
Quick Trick: Match method signature exactly when implementing abstract methods [OK]
Common Mistakes:
  • Not declaring Logger as abstract
  • Missing parameter in abstract method
  • Incorrect file_put_contents flags
  • Trying to declare abstract method in non-abstract class

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes