Bird
0
0

What will be the output of this PHP code?

medium📝 Predict Output Q13 of 15
PHP - Classes and Objects
What will be the output of this PHP code?
<?php
class Car {
  public $color;
  public function __construct($color) {
    $this->color = $color;
  }
  public function getColor() {
    return $this->color;
  }
}
$myCar = new Car('red');
echo $myCar->getColor();
?>
ACar
Bred
Ccolor
DError
Step-by-Step Solution
Solution:
  1. Step 1: Understand the class and constructor

    The class Car has a property $color set by the constructor when creating an object.
  2. Step 2: Trace the code execution

    The object $myCar is created with color 'red'. Calling getColor() returns 'red'.
  3. Final Answer:

    red -> Option B
  4. Quick Check:

    Object property returns 'red' [OK]
Quick Trick: Constructor sets property; method returns it [OK]
Common Mistakes:
  • Confusing class name with property value
  • Expecting 'color' string output
  • Thinking code causes error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes