Bird
0
0

What will be the output of the following PHP code?

medium📝 Predict Output Q13 of 15
PHP - Classes and Objects

What will be the output of the following PHP code?

class Dog {
  public $name;
  public function __construct($name) {
    $this->name = $name;
  }
  public function bark() {
    return "Woof! I am " . $this->name;
  }
}

$dog = new Dog("Buddy");
echo $dog->bark();
AWoof! I am Buddy
BWoof! I am $name
CError: Undefined property
DWoof! I am
Step-by-Step Solution
Solution:
  1. Step 1: Understand constructor usage

    The constructor sets the name property to "Buddy" when the object is created.
  2. Step 2: Analyze the bark method output

    The bark() method returns "Woof! I am " concatenated with the name property, which is "Buddy".
  3. Final Answer:

    Woof! I am Buddy -> Option A
  4. Quick Check:

    Constructor sets name, bark returns it [OK]
Quick Trick: Constructor sets data; methods use it [OK]
Common Mistakes:
  • Ignoring constructor parameters
  • Using variable name instead of property
  • Expecting syntax error due to missing parentheses

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes