Engineering Core
ISB Vietnam's skilled software engineers deliver high-quality applications, leveraging their extensive experience in developing financial tools, business management systems, medical technology, and mobile/web platforms.

While developing PHP applications, IDEs like PhpStorm or Visual Studio Code can help you quickly detect and fix errors. However, there are error cases that the IDE cannot detect, such as:

  • Type errors: IDEs cannot check the data types of variables when they are passed between functions or methods.
  • Call to undefined method errors: IDEs cannot check the calling of methods of an object if they are not defined.
  • Accessing non-existing elements of an array or object: IDEs cannot check accessing non-existing elements of an array or object.
  • ...

PHPStan is a static analysis tool for PHP code that helps detect errors in source code that regular IDEs cannot detect. Unlike dynamic analysis tools that identify issues during runtime, PHPStan performs its analysis by examining the codebase without actually running the application. This approach allows developers to catch errors and potential problems before deploying the code.

Key Features of PHPStan:

  1. Static Analysis: PHPStan analyzes your code without running it, identifying a wide range of potential issues such as type mismatches, undefined variables, and unreachable code.
  2. Type Inference: By analyzing the code flow, PHPStan can infer types of variables, enabling early detection of type-related errors and improving the overall reliability of your code.
  3. Error Detection: It flags common mistakes and potential bugs in your code, helping you catch errors early in the development process.
  4. Customizable Rules: PHPStan allows you to define your own rules and levels of strictness, tailoring the analysis to your specific project requirements.
  5. Integration: It seamlessly integrates with popular PHP development tools and continuous integration pipelines, making it easy to incorporate into your existing workflow.

Benefits of Using PHPStan:

  1. Early Issue Detection: PHPStan finds problems in your code before it runs, helping to catch and prevent bugs early.
  2. Better Code Quality: PHPStan points out areas where your code can be improved, which helps make your code easier to maintain and understand.
  3. Increased Developer Efficiency: Developers get immediate feedback in their coding environment, which speeds up development and reduces time spent debugging.
  4. Type Safety: PHPStan checks types in your code, making it safer and less likely to have runtime errors caused by type mismatches.
  5. Customizable Rules: You can customize PHPStan to fit your project’s requirements by creating your own rules and extensions, ensuring it follows your coding standards.

How to use PHPStan:

To start using PHPStan, follow these simple steps:

  1. Organize project structure:

    Below is an example of a simple directory structure for a project using PHPStan:

    project_root/

    ├── src/ # Directory containing the PHP source code of the application
    │ ├── index.php

    ├── vendor/ # Directory containing libraries and Composer dependencies
    │ └── ...

    ├── phpstan.neon # PHPStan configuration file
    └── composer.json # Composer configuration file

  2. Install PHPStan using Composer

    composer require --dev phpstan/phpstan

  3. Create PHPStan Configuration:

    Add config to phpstan.neon configuration file. This file can define rules, paths to analyze, and other configuration options.

    Example phpstan.neon configuration:

    parameters:
      level: 7
      phpVersion: 80000
      paths:
        - src

    + level: This sets the strictness level of PHPStan to 7, indicating a high level of analysis.
    + phpVersion: Configuration option specifies the PHP version that PHPStan should use for analysis. In this case, 80000 corresponds to PHP version 8.0.0.
    + paths: Specifies the directories to analyze.

  4. Run PHPStan:

    We will add some error code examples to the index.php file for PHPStan to check.

    index.php

    1   <?php
    2   // Using an undeclared variable
    3   echo $undefinedVariable;
    4   
    5   // Calling a non-existent function
    6   nonExistentFunction();
    7   
    8   // Calling a non-existent method within a class
    9   class AnotherClass {
    10       public function method() {
    11           $this->undefinedMethod();
    12       }
    13   }
    14
    15  $anotherObj = new AnotherClass();
    16  $anotherObj->method();
    17
    18  // Performing an operation on a non-numeric variable
    19  $nonNumeric = 'abc';
    20  $result = $nonNumeric * 2;
    21
    22  // Using a global variable
    23  function testGlobal() {
    24      global $undefinedGlobal;
    25      echo $undefinedGlobal;
    26  }
    27
    28  testGlobal();
    29
    30  // Using a function with an inappropriate number of parameters
    31  function sum($a, $b) {
    32      return $a + $b;
    33  }
    34
    35  $result = sum(5);
    36
    37  // Accessing a non-existent element in an array
    38  $array = ['a', 'b', 'c'];
    39  echo $array[3];
    40  ?>


    After that, Run PHPStan from the command line in your project directory:

    vendor/bin/phpstan analyse

  5. Review the Output:

    PHPStan will analyze your code and provide feedback on any issues found. Review the output to identify and fix potential problems in your code.

    Note: Using configuration file /var/www/html/phpstan.neon.
     1/1 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%
     ------ ---------------------------------------------------------------------
      Line   index.php
     ------ ---------------------------------------------------------------------
      3      Variable $undefinedVariable might not be defined.
      6      Function nonExistentFunction not found.
             ? Learn more at https://phpstan.org/user-guide/discovering-symbols
      10     Method AnotherClass::method() has no return type specified.
      11     Call to an undefined method AnotherClass::undefinedMethod().
      20     Binary operation "*" between 'abc' and 2 results in an error.
      23     Function testGlobal() has no return type specified.
      31     Function sum() has no return type specified.
      31     Function sum() has parameter $a with no type specified.
      31     Function sum() has parameter $b with no type specified.
      35     Function sum invoked with 1 parameter, 2 required.
      39     Offset 3 does not exist on array{'a', 'b', 'c'}.
     ------ ---------------------------------------------------------------------
     [ERROR] Found 11 errors

Conclusion:

PHPStan is a valuable tool for any PHP developer looking to write cleaner, more reliable code. By catching errors early and providing detailed feedback, it empowers developers to build high-quality PHP applications with confidence and efficiency.

References:

Written by
Author Avatar
Engineering Core
ISB Vietnam's skilled software engineers deliver high-quality applications, leveraging their extensive experience in developing financial tools, business management systems, medical technology, and mobile/web platforms.

COMPANY PROFILE

Please check out our Company Profile.

Download

COMPANY PORTFOLIO

Explore my work!

Download

ASK ISB Vietnam ABOUT DEVELOPMENT

Let's talk about your project!

Contact US