PHPackages                             smeghead/php-variable-hard-usage - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. smeghead/php-variable-hard-usage

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

smeghead/php-variable-hard-usage
================================

A CLI tool that parses the PHP variable hard usage.

v0.0.8(1y ago)181Apache-2.0PHPPHP &gt;=8.1CI passing

Since Mar 15Pushed 1y ago1 watchersCompare

[ Source](https://github.com/smeghead/php-variable-hard-usage)[ Packagist](https://packagist.org/packages/smeghead/php-variable-hard-usage)[ RSS](/packages/smeghead-php-variable-hard-usage/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (9)Dependencies (4)Versions (10)Used By (0)

PHP CLI Tool for Analyzing Local Variable Usage
===============================================

[](#php-cli-tool-for-analyzing-local-variable-usage)

Overview
--------

[](#overview)

This PHP CLI tool analyzes the usage of local variables in PHP source code, focusing on their scope and update frequency. It helps developers identify potential issues in handling local variables, improving code quality and maintainability.

[![Testing](https://github.com/smeghead/php-variable-hard-usage/actions/workflows/php.yml/badge.svg?event=push)](https://github.com/smeghead/php-variable-hard-usage/actions/workflows/php.yml/badge.svg?event=push) [![Latest Stable Version](https://camo.githubusercontent.com/6313e9411d9f0cfe80820d799fab2c341f11d4c62720437188ce3edde75fd346/68747470733a2f2f706f7365722e707567782e6f72672f736d6567686561642f7068702d7661726961626c652d686172642d75736167652f76)](https://packagist.org/packages/smeghead/php-variable-hard-usage) [![Total Downloads](https://camo.githubusercontent.com/52b5c6e82c9bfa9b251703234bd33ec6facf3571f599bcc948bcdd1bff3998aa/68747470733a2f2f706f7365722e707567782e6f72672f736d6567686561642f7068702d7661726961626c652d686172642d75736167652f646f776e6c6f616473)](https://packagist.org/packages/smeghead/php-variable-hard-usage) [![Latest Unstable Version](https://camo.githubusercontent.com/148846e6e47e9d7fa3092963b617ed691bdbe0a67cccf3dbb2be950e7e35c684/68747470733a2f2f706f7365722e707567782e6f72672f736d6567686561642f7068702d7661726961626c652d686172642d75736167652f762f756e737461626c65)](https://packagist.org/packages/smeghead/php-variable-hard-usage) [![License](https://camo.githubusercontent.com/d027034bc3d9531a974b2901bf564987f7e74817674c556a8714966868be253e/68747470733a2f2f706f7365722e707567782e6f72672f736d6567686561642f7068702d7661726961626c652d686172642d75736167652f6c6963656e7365)](https://packagist.org/packages/smeghead/php-variable-hard-usage) [![PHP Version Require](https://camo.githubusercontent.com/550c067ae15615a27c0ce47e26e6cb5f13a333a011d9754700b86c4d89e96a0a/68747470733a2f2f706f7365722e707567782e6f72672f736d6567686561642f7068702d7661726961626c652d686172642d75736167652f726571756972652f706870)](https://packagist.org/packages/smeghead/php-variable-hard-usage)

What is "Local Variable Hard Usage"?
------------------------------------

[](#what-is-local-variable-hard-usage)

"Local Variable Hard Usage" is a concept that evaluates how intensely local variables are used in a function or method. This metric helps identify variables that might negatively impact code readability and maintainability due to excessive scope width and frequent updates.

The idea behind this metric is that when a local variable is referenced over a wide range of lines or is frequently modified, it becomes harder to understand and refactor. By quantifying this, we can gain insights into potential problem areas in the code.

This concept is introduced and explained in detail in the following blog post: [Understanding Local Variable Hard Usage](https://blog.starbug1.com/archives/3022)

This tool analyzes PHP code using PHP-Parser to measure the "Local Variable Hard Usage" for each function and method. It calculates the average reference line span of each variable and sums the deviations from this average, providing a score that represents how heavily a variable is used within its scope.

Features
--------

[](#features)

- Analyzes local variable scope and update frequency.
- Provides insights into variable usage patterns.
- Helps identify potential issues related to variable handling.

Installation
------------

[](#installation)

To install the PHP CLI tool, follow these steps:

1. Clone the repository:

    ```
    git clone https://github.com/smeghead/php-variable-hard-usage.git
    cd php-variable-hard-usage
    ```
2. Install dependencies using Composer:

    ```
    composer install
    ```

Alternatively, you can install the tool via Composer as a development dependency:

```
composer require --dev smeghead/php-variable-hard-usage
```

Usage
-----

[](#usage)

The tool provides two operation modes: `single` mode for analyzing individual files and `scopes` mode for analyzing multiple files or directories.

### Single File Analysis

[](#single-file-analysis)

Use the `single` command to analyze a single PHP file:

```
$ vendor/bin/php-variable-hard-usage single path/to/your-file.php
{
    "filename": "path/to/your-file.php",
    "maxVariableHardUsage": 65,
    "avarageVariableHardUsage": 26.833333333333332,
    "scopes": [
        {
            "namespace": "Smeghead\\PhpVariableHardUsage\\Parse",
            "name": "VariableParser::__construct",
            "variableHardUsage": 1
        },
        {
            "namespace": "Smeghead\\PhpVariableHardUsage\\Parse",
            "name": "VariableParser::resolveNames",
            "variableHardUsage": 9
        },
        {
            "namespace": "Smeghead\\PhpVariableHardUsage\\Parse",
            "name": "VariableParser::parse",
            "variableHardUsage": 39
        }
    ]
}
```

For backward compatibility, you can also run without specifying the `single` command:

```
$ vendor/bin/php-variable-hard-usage path/to/your-file.php
```

### Multiple Files Analysis

[](#multiple-files-analysis)

Use the scopes command to analyze multiple files or entire directories:

```
# Analyze all PHP files in a directory
$ vendor/bin/php-variable-hard-usage scopes src/

# Analyze multiple directories
$ vendor/bin/php-variable-hard-usage scopes src/ tests/

# Analyze specific files and directories
$ vendor/bin/php-variable-hard-usage scopes src/Command.php config/ tests/
```

The output for scopes mode is a combined report with results sorted by variable hard usage:

```
{
    "scopes": [
        {
            "file": "src/Parse/VariableParser.php",
            "namespace": "Smeghead\\PhpVariableHardUsage\\Parse",
            "name": "VariableParser::collectParseResultPerFunctionLike",
            "variableHardUsage": 65
        },
        {
            "file": "src/Parse/VariableParser.php",
            "namespace": "Smeghead\\PhpVariableHardUsage\\Parse",
            "name": "Expr_Closure@65",
            "variableHardUsage": 47
        },
        {
            "file": "src/Parse/VariableParser.php",
            "namespace": "Smeghead\\PhpVariableHardUsage\\Parse",
            "name": "VariableParser::parse",
            "variableHardUsage": 39
        }
    ]
}
```

### CI Integration with Check Mode

[](#ci-integration-with-check-mode)

Use the check command with an optional threshold to analyze files and enforce variable usage standards in CI/CD pipelines:

```
# Check files with default threshold (200)
$ vendor/bin/php-variable-hard-usage check src/

# Check with custom threshold
$ vendor/bin/php-variable-hard-usage check --threshold=500 src/ tests/

# Check specific files and directories
$ vendor/bin/php-variable-hard-usage check --threshold=300 src/Command.php config/
```

The check mode returns different exit codes based on the result:

- Exit code 0: Success - No analysis errors and no scopes exceeding the threshold
- Exit code 1: Analysis failure - Errors occurred during file parsing or analysis
- Exit code 2: Threshold exceeded - One or more scopes exceeded the specified variable hard usage threshold

The output includes the threshold used, result status, and a list of scopes that exceeded the threshold:

```
{
    "threshold": 500,
    "result": "failure",
    "scopes": [
        {
            "file": "src/Parse/VariableParser.php",
            "namespace": "Smeghead\\PhpVariableHardUsage\\Parse",
            "name": "VariableParser::collectParseResultPerFunctionLike",
            "variableHardUsage": 655
        },
        {
            "file": "src/Command/SingleCommand.php",
            "namespace": "Smeghead\\PhpVariableHardUsage\\Command",
            "name": "SingleCommand::execute",
            "variableHardUsage": 530
        }
    ]
}
```

This mode is particularly useful for integrating the tool into your CI/CD pipeline to fail builds when variable usage exceeds acceptable thresholds.

### Help and Version Information

[](#help-and-version-information)

To display help information:

```
$ vendor/bin/php-variable-hard-usage --help
```

```
$ vendor/bin/php-variable-hard-usage --version
```

How to calculate VariableHardUsage
----------------------------------

[](#how-to-calculate-variablehardusage)

VariableHardUsage is an index used to evaluate the frequency of use and scope of local variables within a function. This measure is calculated based on the variance of the line number of references to the same variable and the frequency with which the variable is assigned.

### Calculation Procedure

[](#calculation-procedure)

This tool calculates the **Variable Hard Usage** score for each **scope** (i.e., a function or method) based on how local variables are used. The calculation consists of the following steps:

#### 1. Extract local variables in a scope

[](#1-extract-local-variables-in-a-scope)

For each scope $S$, extract all local variables:

$V = {v\_1, v\_2, ..., v\_m}$

#### 2. For each variable $v\_j$, identify lines where it is referenced

[](#2-for-each-variable-v_j-identify-lines-where-it-is-referenced)

Let the variable $v\_j$ be referenced at line numbers:

$L^{(j)} = {l^{(j)}\_1, l^{(j)}\_2, ..., l^{(j)}\_{n\_j}} \\quad$

#### 3. Assign weights to each reference

[](#3-assign-weights-to-each-reference)

Each reference line $l^{(j)}\_i$ is assigned a weight $w^{(j)}\_i$ depending on whether it is a simple read or an assignment:

- If the reference is **an assignment (update)**:
    $w^{(j)}\_i = \\alpha \\quad (\\text{default: } \\alpha = 2)$
- If the reference is **a read-only access**:
    $w^{(j)}\_i = 1$

#### 4. Calculate Variable Hard Usage for each variable

[](#4-calculate-variable-hard-usage-for-each-variable)

Let $l^{(j)}\_\\text{base} = l^{(j)}\_1$, the first line where $v\_j$ appears.

Then, the hard usage score for $v\_j$ is calculated as:

$H(v\_j) = \\sum\_{i=1}^{n\_j} w^{(j)}\_i \\cdot |l^{(j)}\_i - l^{(j)}\_\\text{base}|$

This measures how widely and intensely the variable is used, with updates having a stronger impact.

#### 5. Sum all variable scores to get the score for the scope

[](#5-sum-all-variable-scores-to-get-the-score-for-the-scope)

The total **Variable Hard Usage** for the scope $S$ is:

$H(S) = \\sum\_{j=1}^{m} H(v\_j) = \\sum\_{j=1}^{m} \\sum\_{i=1}^{n\_j} w^{(j)}\_i \\cdot |l^{(j)}\_i - l^{(j)}\_\\text{base}|$

A larger value of $H(S)$ indicates that variables in the scope are heavily and broadly used, which may reduce code readability and maintainability.

### Example

[](#example)

Suppose, for example, that there are three reference points in a function, each with line numbers 10, 20, and 30, and that some assignments are made and some are not made. In this case, the line number of the first occurrence is 10.

- Reference A: line 10, with assignment
- Reference B: line 20, no assignment
- Reference C: line 30, with assignment

In this case, VariableHardUsage is calculated as follows

- Reference A: (10 - 10) \* 2 = 0
- Reference B: (20 - 10) \* 1 = 10
- Reference C: (30 - 10) \* 2 = 40

Summing these, VariableHardUsage is 0 + 10 + 40 = 50.

VariableHardUsage is thus calculated as a measure of the frequency of use and scope of a variable. This metric can be used to quantitatively evaluate the usage of local variables within a function and help improve code readability and maintainability.

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance46

Moderate activity, may be stable

Popularity7

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 88.8% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

9

Last Release

416d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/179acd76bf9ce4197915822481df9901a4f70435e3b2152160b0b227146b9d95?d=identicon)[smeghead](/maintainers/smeghead)

---

Top Contributors

[![smeghead](https://avatars.githubusercontent.com/u/112476?v=4)](https://github.com/smeghead "smeghead (71 commits)")[![hirokinoue](https://avatars.githubusercontent.com/u/70567194?v=4)](https://github.com/hirokinoue "hirokinoue (9 commits)")

---

Tags

variable usage

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/smeghead-php-variable-hard-usage/health.svg)

```
[![Health](https://phpackages.com/badges/smeghead-php-variable-hard-usage/health.svg)](https://phpackages.com/packages/smeghead-php-variable-hard-usage)
```

###  Alternatives

[symfony/maker-bundle

Symfony Maker helps you create empty commands, controllers, form classes, tests and more so you can forget about writing boilerplate code.

3.4k111.1M568](/packages/symfony-maker-bundle)[roave/backward-compatibility-check

Tool to compare two revisions of a public API to check for BC breaks

5953.3M56](/packages/roave-backward-compatibility-check)[coenjacobs/mozart

Composes all dependencies as a package inside a WordPress plugin

4723.6M20](/packages/coenjacobs-mozart)[psalm/plugin-laravel

Psalm plugin for Laravel

3274.9M308](/packages/psalm-plugin-laravel)[recca0120/laravel-erd

Laravel ERD automatically generates Entity-Relationship Diagrams from your Laravel models and displays them using Vuerd.

36072.0k](/packages/recca0120-laravel-erd)[ondrejmirtes/better-reflection

Better Reflection - an improved code reflection API

136.2M4](/packages/ondrejmirtes-better-reflection)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
