Use get_defined_vars() when you need to returns variables visible in the current scope in a PHP application. The examples below show the actual operation and its limitations.
What Is get_defined_vars() in PHP?
Returns variables visible in the current scope. The exact signature supported by your installation depends on its PHP version and enabled extensions.
Its syntax is:
get_defined_vars(): array
Parameters and return value: The parameter types, optional arguments, references, and return type are shown in the signature above. Optional parameters are marked with an ellipsis in this reference signature.
Example 1: Basic Usage
<?php
function scopeExample() { $username = "Alex"; return array_keys(get_defined_vars()); } print_r(scopeExample());
Result: Run the example in an environment that supports the function. Any values depending on operating-system state, installed extensions, process configuration, or network access must be checked on the target server.
Example 2: Different Input or Behavior
<?php
function localsExample() { $count = 2; return get_defined_vars()["count"]; } echo localsExample();
Result: Run the example in an environment that supports the function. Any values depending on operating-system state, installed extensions, process configuration, or network access must be checked on the target server.
Practical Example: Applying the Function
<?php
function debugOrder($orderId, $total) { $vars = get_defined_vars(); return isset($vars["orderId"],$vars["total"]); } var_dump(debugOrder(5, 20));
Result: Run the example in an environment that supports the function. Any values depending on operating-system state, installed extensions, process configuration, or network access must be checked on the target server.
Important Behavior and Edge Cases
Never dump all variables in production: they may include secrets or personally identifiable data.
Comparison With Related Functions
| Approach | Difference |
|---|---|
get_defined_vars() | Returns variables visible in the current scope. |
| Related operation | compact() selects named variables; get_defined_vars() returns all visible variables. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring the function-specific limitation | Never dump all variables in production: they may include secrets or personally identifiable data. |
| Confusing this function with a related operation | compact() selects named variables; get_defined_vars() returns all visible variables. |
Key Takeaways
- Returns variables visible in the current scope.
- Never dump all variables in production: they may include secrets or personally identifiable data.
- compact() selects named variables; get_defined_vars() returns all visible variables.
Use get_defined_vars() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.