Bird
0
0

What will be the output of the following PHP code?

medium📝 Predict Output Q5 of 15
PHP - Classes and Objects
What will be the output of the following PHP code?
class Score {
  private $points = 0;
  public function addPoint() {
    $this->points++;
  }
  public function getPoints() {
    return $this->points;
  }
}
$score = new Score();
$score->addPoint();
$score->addPoint();
$score->addPoint();
echo $score->getPoints();
A3
B0
C1
DError
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the class

    The class Score has a private property $points initialized to 0.

  2. Step 2: Method calls

    Each call to addPoint() increments $points by 1.

  3. Step 3: Counting increments

    Three calls to addPoint() increase $points from 0 to 3.

  4. Step 4: Output

    getPoints() returns 3, which is echoed.

  5. Final Answer:

    3 -> Option A
  6. Quick Check:

    Increment thrice, output is 3 [OK]
Quick Trick: Increment private property via $this-> [OK]
Common Mistakes:
  • Assuming property does not increment
  • Confusing private property access
  • Expecting error due to private visibility

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes