Bird
0
0

What will be the output of the following PHP code?

medium📝 Predict Output Q4 of 15
PHP - Classes and Objects
What will be the output of the following PHP code?
class Sample {
  private $value = 10;
  public function getValue() {
    return $this->value;
  }
}
$obj = new Sample();
echo $obj->getValue();
AError: Cannot access private property
B10
Cnull
D0
Step-by-Step Solution
Solution:
  1. Step 1: Understand private property access

    The private property $value is accessed inside the class via the public method getValue(). This is allowed.
  2. Step 2: Check method call and output

    Calling getValue() returns 10, which is then echoed.
  3. Final Answer:

    10 -> Option B
  4. Quick Check:

    Private accessed via public method = 10 [OK]
Quick Trick: Private properties can be accessed inside class methods [OK]
Common Mistakes:
  • Thinking private blocks access even inside class
  • Expecting error on method call
  • Confusing property with method access

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes