---
title: No Duplicate Variable Names In Scope
impact: HIGH
impactDescription: prevents variable shadowing bugs and improves code clarity
tags: variables, shadowing, scope, quality, php
---

## No Duplicate Variable Names In Scope

Variable shadowing occurs when a variable declared within a certain scope (like a function or a closure) has the same name as a variable in an outer scope. This can lead to subtle bugs and makes the code difficult to follow.

**Incorrect (shadowed variables):**

```php
$user = Auth::user();

function updateProfile($request) {
    // Shadows the potentially global or outer $user
    $user = $request->input('user_data'); 
    
    // Which $user is this?
    $user->save();
}

// Shadowing in loops
foreach ($orders as $order) {
    $order = $this->repository->enhance($order); // Shadowing the loop variable
}
```

**Correct (unique names):**

```php
$currentUser = Auth::user();

function updateProfile($request) {
    $profileData = $request->input('user_data');
    
    $profileData->save();
}

foreach ($orders as $order) {
    $enhancedOrder = $this->repository->enhance($order);
}
```

**Shadowing in Closures (PHP):**
Be careful when using `use` in anonymous functions:
```php
$message = "Hello";

$callback = function($input) use ($message) {
    $message = $input; // Shadows the captured $message (only locally)
};
```

**Why avoid shadowing?**
- **Clarity**: Developers don't have to keep track of multiple meanings for the same variable name.
- **Bug Prevention**: Avoids accidentally overwriting or reading the wrong value when scopes are nested or side effects occur.

**Tools:** PHPStan, Psalm, PHP_CodeSniffer
