Bird
0
0

Given the class below, what will be the output?

hard📝 Application Q15 of 15
PHP - Classes and Objects
Given the class below, what will be the output?
class Counter {
  private $count = 0;
  public function increment() {
    $this->count++;
  }
  public function getCount() {
    return $this->count;
  }
}
$c = new Counter();
$c->increment();
$c->increment();
echo $c->getCount();
AError: Cannot access private property
B2
C1
D0
Step-by-Step Solution
Solution:
  1. Step 1: Understand property increment inside the class

    The increment() method increases the private $count property by 1 each time it is called.
  2. Step 2: Trace method calls and final output

    Calling increment() twice increases $count from 0 to 2. Then getCount() returns 2.
  3. Final Answer:

    2 -> Option B
  4. Quick Check:

    Two increments = count 2 [OK]
Quick Trick: Private properties accessed via $this inside class work fine [OK]
Common Mistakes:
  • Assuming private properties can't be accessed inside class methods
  • Forgetting that increment operator changes value
  • Expecting output before increments

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes