Bird
0
0

What will be the output of this PHP code?

medium📝 Predict Output Q5 of 15
PHP - Classes and Objects
What will be the output of this PHP code?
class Car {
  public $color = "red";
  public function getColor() {
    return $this->color;
  }
}
$myCar = new Car();
echo $myCar->getColor();
Acolor
Bred
C$this->color
DError
Step-by-Step Solution
Solution:
  1. Step 1: Understand method returning property

    The method getColor() returns the value of the property color which is "red".
  2. Step 2: Predict output of echo

    Calling $myCar->getColor() returns "red", which is printed.
  3. Final Answer:

    red -> Option B
  4. Quick Check:

    Method returns property value = red [OK]
Quick Trick: Use $this->property inside class methods [OK]
Common Mistakes:
  • Printing property name instead of value
  • Using $this outside class
  • Expecting error due to method call

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes