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?
class Car {
  private $color = 'red';
  public function getColor() {
    return $this->color;
  }
}
$car = new Car();
echo $car->getColor();
AEmpty string
BError: Cannot access private property
Cnull
Dred
Step-by-Step Solution
Solution:
  1. Step 1: Understand private property access

    The property $color is private, so it cannot be accessed directly outside the class.
  2. Step 2: Check method usage to access private property

    The public method getColor() returns the private property value, so calling it outputs 'red'.
  3. Final Answer:

    red -> Option D
  4. Quick Check:

    Private property accessed via public method = 'red' [OK]
Quick Trick: Use public methods to access private properties safely [OK]
Common Mistakes:
  • Trying to access private property directly
  • Expecting an error when using a getter method
  • Confusing null with private property value

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes