Bird
0
0

Identify the error in this code:

medium📝 Debug Q7 of 15
PHP - Classes and Objects

Identify the error in this code:

class Fruit {
public $name;
function __construct() {
$this->name = 'Apple';
}
}
$f = Fruit();
echo $f->name;
AConstructor should have parameters.
BProperty <code>name</code> is private.
CMissing <code>new</code> keyword when creating object.
DCannot echo object property directly.
Step-by-Step Solution
Solution:
  1. Step 1: Check object instantiation syntax

    The code $f = Fruit(); calls class like a function, which is invalid.
  2. Step 2: Correct syntax requires new

    It should be $f = new Fruit(); to create an object.
  3. Final Answer:

    Missing new keyword when creating object. -> Option C
  4. Quick Check:

    Always use new to instantiate objects [OK]
Quick Trick: Use new before class name to create objects [OK]
Common Mistakes:
  • Calling class as function
  • Expecting constructor parameters mandatory
  • Thinking property visibility causes error here

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes