Bird
0
0

You want to create a PHP class Product that sets name and price when an object is created. Which constructor correctly does this?

hard📝 Application Q8 of 15
PHP - Classes and Objects
You want to create a PHP class Product that sets name and price when an object is created. Which constructor correctly does this?
class Product {
  public $name;
  public $price;
  public function __construct($name, $price) {
    // Fill in
  }
}
Aname = $name; price = $price;
B$name = $this->name; $price = $this->price;
C$this->name = $name; $this->price = $price;
D$this->name == $name; $this->price == $price;
Step-by-Step Solution
Solution:
  1. Step 1: Assign constructor parameters to object properties

    Use $this->property = parameter to set values correctly.
  2. Step 2: Check each option for correct syntax

    Only $this->name = $name; $this->price = $price; uses correct assignment with $this and single equals.
  3. Final Answer:

    $this->name = $name; $this->price = $price; -> Option C
  4. Quick Check:

    Assign parameters to properties with $this->property = parameter [OK]
Quick Trick: Use $this->property = parameter inside constructor [OK]
Common Mistakes:
  • Reversing assignment order
  • Using == instead of = for assignment
  • Omitting $this keyword

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes