Bird
0
0

Examine this PHP code:

medium📝 Debug Q7 of 15
PHP - Classes and Objects
Examine this PHP code:
<?php
class User {
  public $name;
  public function __construct($name) {
    $this->name = $name;
  }
}
$user = new User('Alice');
echo $user->name;
?>

What is the purpose of $this->name = $name; inside the constructor?
AIt assigns the passed parameter to the object's property.
BIt declares a new local variable named name.
CIt calls the parent class constructor.
DIt outputs the value of the name property.
Step-by-Step Solution
Solution:
  1. Step 1: Identify $this usage

    $this refers to the current object instance.
  2. Step 2: Understand assignment

    $this->name = $name; assigns the constructor argument to the object's property.
  3. Final Answer:

    It assigns the passed parameter to the object's property. -> Option A
  4. Quick Check:

    $this->property sets object property [OK]
Quick Trick: $this->property accesses object property [OK]
Common Mistakes:
  • Confusing $name with $this->name
  • Thinking it declares a local variable
  • Assuming it calls a parent constructor

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes