Difficulty: Easy
Correct Answer: 5, because $$b refers to the variable whose name is stored in $b, which in this case is $a.
Explanation:
Introduction / Context:
This question focuses on the concept of variable variables in PHP. Variable variables allow you to use the value of one variable as the name of another variable. Although this can be confusing, it often appears in interview questions to test whether you understand how PHP resolves variable names at runtime.
Given Data / Assumptions:
Concept / Approach:
In PHP, a variable variable is written as $$name, where $name contains the name of another variable. When PHP evaluates $$name, it first looks at the value stored in $name and then treats that value as the actual variable name to resolve. So if $name contains the string test, $$name refers to $test. This feature is powerful but can reduce readability and should be used carefully.
Step-by-Step Solution:
Step 1: Start with the given assignments: $a = 5; and $b = "a";.Step 2: Recognise that $b holds the string a, which is the name of the first variable without its dollar symbol.Step 3: When PHP evaluates $$b, it first reads the value of $b, which is a.Step 4: PHP then interprets $$b as $a, because the value of $b is the string a.Step 5: Since $a has the value 5, the final result of $$b is 5, which matches option A.
Verification / Alternative check:
You can confirm this by writing a simple script: $a = 5; $b = "a"; echo $$b; The output will be 5. If you change $b to "c" and define $c = 10; then $$b would resolve to $c and output 10. This behaviour clearly illustrates that $$b is a variable variable whose target is determined by the string stored in $b.
Why Other Options Are Wrong:
Option B claims that $$b returns the original character stored in $b, which ignores the variable variable mechanism. Option C is incorrect because PHP does support variable variables. Option D suggests that a string "$a" is created, but in reality $$b resolves to the value of $a, not a literal string containing its name.
Common Pitfalls:
Variable variables can quickly become confusing when nested deeply or combined with arrays and objects. It is easy to lose track of what each symbol refers to, which can lead to bugs that are hard to trace. Many modern coding standards recommend using associative arrays or maps instead of variable variables for dynamic data structures. However, understanding variable variables remains useful for reading legacy or framework code that relies on this feature.
Final Answer:
5, because $$b refers to the variable whose name is stored in $b, which in this case is $a.
Discussion & Comments