Skip to content

Comparison with Other Tools ​

The PHP ecosystem has a rich set of tools for type safety, validation, and performance. Because they operate at different stages of your application's lifecycle, many of them are complementary partners to TypePHP rather than direct replacements.


At a Glance ​

ToolCategoryWhen It RunsUses Existing PHPDocs?Reified Generics in RAMCatches Dynamic Data (DB / JSON / DI)Standard PHP 8.1+ Drop-In
TypePHP (typephp/typephp)Runtime Type CheckerRuntime (LTW / OPcache)Yes (zero boilerplate)Yes (\WeakMap)YesYes
PHPStanStatic AnalyzerOffline / CI / IDEYesNo (compile-time only)NoYes
PsalmStatic AnalyzerOffline / CI / IDEYesNo (compile-time only)NoYes
PhanStatic AnalyzerOffline / CIYesNo (compile-time only)NoYes
MagoStatic Analyzer / ToolchainOffline / CI / IDEYesNo (compile-time only)NoYes
beberlei/assertAssertion LibraryRuntimeNo (manual calls)NoYes (where written)Yes
webmozart/assertAssertion LibraryRuntimeNo (manual calls)NoYes (where written)Yes
Native assert()Language ConstructRuntime (dev only)No (manual calls)NoYes (where written)Yes
cuyz/valinorObject Mapper / HydratorRuntime (at map())Yes (DTO hydration)No (validates on map)Yes (at map boundary)Yes
azjezz/psl (Psl\Type)Runtime Type CombinatorsRuntimeNo (explicit schemas)NoYes (where called)Yes
Swoole TypePHP (swoole/typephp)AOT PHP-to-C++ CompilerBuild-Time -> Native BinarySubset / Typed PHPC++ ContainersCompile-time subsetNo (AOT subset)

1. Static Analyzers: PHPStan, Psalm, Phan & Mago ​

TL;DR: Partners, not replacements. Static analyzers verify your source code before it runs, while TypePHP verifies live runtime data where static analyzers are blind.

  • PHPStan: The most widely adopted PHP static analyzer, featuring strictness levels from 0 to 10 (MAX) and an extensive framework extension ecosystem (Larastan, Symfony, Doctrine).
  • Psalm: Static analyzer known for deep generic inference, immutability checks, security taint analysis, and pioneering @psalm-this-out.
  • Phan: Long-standing AST-based static analyzer designed to minimize false positives across large and legacy PHP codebases.
  • Mago: A modern Rust-based unified PHP toolchain combining a high-speed static analyzer, linter, formatter, and architectural guard in a single native binary.

Where Static Analyzers Excel ​

  • Catching undefined methods, typos, dead code paths, and broken call graphs instantly without executing your code.
  • Verifying branches that your test suite may never execute.
  • Adding 0% runtime execution overhead in production.

Where Static Analyzers Are Blind (And TypePHP Steps In) ​

Static analyzers never execute your application. They reason about source text rather than live heap memory, which leaves several runtime blind spots:

  • Dynamic I/O Boundaries: Decoded JSON payloads, webhook bodies, PDO database rows, and Redis cache entries.
  • Compiled DI Containers & Proxies: Framework service containers (Symfony, Laravel, Shopware) injecting an unexpected concrete or generic instance at runtime.
  • Untyped & Shared-Reference Boundaries: Objects crossing untyped object or mixed middleware, or mutated through shared variable aliases ($shared = $session; $session->login();).
  • Runtime Generic State: Guaranteeing a Collection<User> cannot be polluted with a Product downstream after passing through un-annotated code.

Seamless Interoperability ​

TypePHP does not invent its own annotation dialect. It reads your existing annotations using the priority hierarchy @phpstan-* > @psalm-* > @*, and can directly load existing PHPStan or Psalm Stub Files for third-party vendor packages.

Try running the live SQLite example below. In real codebases, developers often narrow a PDO::fetch() result with an inline @var annotation so static analysis passes cleanly. Because static analyzers cannot inspect your live database tables, they trust that annotation blindly, whereas TypePHP verifies the actual database row at runtime:

Closing the Static Analysis Runtime Blind Spot (SQLite PDO)
php
<?php

declare(strict_types=1);

class UserRepository
{
    public function __construct(private PDO $pdo) {}

    /**
     * Static analyzers trust this contract at compile time,
     * but cannot see what actually lives in the database at runtime.
     *
     * @return array{id: positive-int, username: non-empty-string, role: 'admin'|'member'}
     */
    public function findById(int $id): array
    {
        $stmt = $this->pdo->prepare('SELECT id, username, role FROM users WHERE id = ?');
        $stmt->execute([$id]);

        /** @var array{id: positive-int, username: non-empty-string, role: 'admin'|'member'} $row */
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        return $row;
    }
}

$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE users (id INTEGER, username TEXT, role TEXT)');

// Row 1 is valid; Row 2 simulates corrupted legacy data or a bad migration
$pdo->exec("INSERT INTO users VALUES (1, 'Alice', 'admin')");
$pdo->exec("INSERT INTO users VALUES (-10, '', 'superadmin')");

$repo = new UserRepository($pdo);

// 1. Valid database row passes cleanly
$alice = $repo->findById(1);
echo "✓ Loaded user #{$alice['id']}: {$alice['username']} ({$alice['role']})\n\n";

// 2. Corrupted database row is caught immediately at runtime before leaking downstream
echo "Fetching corrupted legacy row from SQLite...\n";
$repo->findById(-10);

2. Imperative Assertion Libraries: beberlei/assert, webmozart/assert & Native assert() ​

Libraries like beberlei/assert and webmozart/assert (as well as PHP's built-in assert() construct) provide imperative runtime guard clauses inside method bodies.

The Core Difference: Declarative Contracts vs. Writing Types Twice ​

With imperative assertion libraries, you must repeat your type contracts manually inside every method body: once in the PHPDoc for your IDE and static analyzer, and again as imperative Assert::* calls for PHP at runtime:

php
// Imperative approach (beberlei/assert or webmozart/assert)
use Webmozart\Assert\Assert;

/**
 * @param positive-int $id
 * @param list<non-empty-string> $tags
 * @return array{id: positive-int, tags: list<non-empty-string>}
 */
function publishPost(int $id, array $tags): array
{
    Assert::positiveInteger($id);
    Assert::isList($tags);
    Assert::allStringNotEmpty($tags);

    $result = ['id' => $id, 'tags' => $tags];

    // Return shapes, property writes, and inherited interfaces
    // must also be asserted manually everywhere they are used.
    return $result;
}

With TypePHP, your existing PHPDoc is the runtime contract, giving you zero manual guard clauses along with automatic coverage for @return, class properties, PHP 8.4 hooks, @param-out, interface inheritance, and \WeakMap reified generics:

Declarative Enforcement with Zero Assertion Boilerplate
php
<?php

declare(strict_types=1);

/**
 * @param positive-int $id
 * @param list<non-empty-string> $tags
 * @return array{id: positive-int, tags: list<non-empty-string>}
 */
function publishPost(int $id, array $tags): array
{
    return ['id' => $id, 'tags' => $tags];
}

// 1. Valid call
$post = publishPost(42, ['php', 'typephp']);
echo "✓ Published post #{$post['id']} (" . implode(', ', $post['tags']) . ")\n\n";

// 2. Empty tag string caught automatically with zero Assert::* calls!
echo "Passing empty tag string...\n";
publishPost(42, ['php', '']);

When to Choose Each ​

CriterionTypePHPbeberlei/assert / webmozart/assertNative PHP assert()
Type Contracts (list<T>, shapes, generics)Automatic from PHPDocsManual calls per parameterManual boolean expressions
Domain Business Invariants (e.g. email, UUID, $end > $start, file exists)Not a business validatorExcels hereManual expressions
Return, Property & Interface InheritanceAutomatic across hierarchiesMust be repeated in every implementationMust be repeated manually
Reified Generics (Collection<User>)Native via \WeakMapNot supportedNot supported
1-Pass Audit Mode (report)Built-in JSON audit & shardingThrows on first failureThrows / warns on failure
Zero-Cost Production ToggleTYPEPHP_DISABLE=true / enabled => falseAlways executes in prodZero opcodes with zend.assertions=-1

Best Practice

Use TypePHP for structural and generic type contracts (positive-int, array{...}, Collection<T>, @self-out), and keep webmozart/assert or beberlei/assert for semantic domain invariants that go beyond types (such as valid email addresses, UUID formats, or cross-field business rules like $expiresAt > $createdAt).


3. Runtime Object Mappers & Schema Validators: Valinor, PSL & Framework Validators ​

cuyz/valinor ​

Valinor is a dependency-free PHP library that maps and validates untrusted raw inputs (JSON, arrays, HTTP requests) into strongly typed value objects using PHPDoc types (array shapes, integer ranges, generics), and normalizes objects back out.

  • How Valinor differs from TypePHP: Valinor is an explicit boundary hydrator. It validates and constructs objects at the specific places where you call $mapper->map(MyDto::class, $input), returning structured multi-error mapping trees ideal for API 422 responses. However, it does not guard internal method calls, return statements, property mutations, generators, callables, or mutable generic containers after hydration.
  • How they pair together: Use Valinor at your HTTP or webhook ingress layer to hydrate raw JSON into typed DTOs, and TypePHP throughout your services, repositories, and test suites to guarantee that internal boundaries and generic collections stay honest end-to-end.

azjezz/psl (Psl\Type) ​

PSL's Type component provides composable runtime type combinators (such as Type\shape(...), Type\vec(...), Type\positive_int()) with explicit assert() and coerce() methods alongside first-class static analysis support.

  • How Psl\Type differs from TypePHP: Psl\Type requires you to explicitly build type schema objects and call assert() or coerce() in your source code wherever you want runtime checks. By contrast, TypePHP injects its runtime checks transparently from your existing PHPDoc comments so your source code stays free of manual validation boilerplate, while also providing reified \WeakMap generics, typestates (@self-out), and compile-time AST check elimination.
  • Where Psl\Type still shines: Unlike TypePHP, which strictly validates values without modifying them, Psl\Type also supports explicit type coercion (such as safely coercing '42' from HTTP query strings into int), making it a strong fit for raw ingress parsing.

Framework Validators (Laravel Validation, Symfony Validator, Respect/Validation) ​

Framework validation libraries are built for end-user input validation, including localized human-readable error messages, form field rules (unique:users,email, confirmed, mimes:pdf), and collecting all form errors for UI display. TypePHP is a developer contract enforcer that catches internal programming bugs, stale DocBlocks, and corrupted runtime state rather than replacing user-facing form validation.


4. Same Name, Different Project: TypePHP vs. Swoole TypePHP ​

There are two completely independent open-source projects named TypePHP in the PHP ecosystem. Because they share a name, they are frequently confused, even though they solve completely different problems with opposite architectures.

TypePHP (typephp/typephp, this project)Swoole TypePHP (swoole/typephp)
Core ArchitecturePure-PHP runtime type checker using Load-Time Weaving (file:// StreamWrapper) and \WeakMap reificationAhead-of-Time (AOT) compiler (tpc.php / tpc) translating a typed PHP subset into C++17 and native machine code
Primary GoalEradicate DocBlock lies and bring true reified generics and typestates to standard PHP codebasesCompile CPU-bound PHP code into standalone native executables, PHP extensions (.so), or shared libraries
PHP Version RequirementPHP 8.1+ (pure PHP userland, works on NTS and ZTS)PHP 8.4 or 8.5 (CLI + php-dev headers + php-config; pre-built releases target ZTS)
Installation & Build Toolscomposer require --dev typephp/typephp with zero system dependenciescomposer require --dev swoole/typephp (or release archive), plus GCC 9+ / Clang (C++17), CMake 3.24+, GMP, MPFR, PHPX, and libphp.so / libphp.dylib (Embed SAPI) for binary builds
Runtime TargetStandard Zend Engine (PHP-FPM, CLI, FrankenPHP, RoadRunner, Swoole, WASM)Compiled C++17 native binaries or loaded Zend extensions (extension=...)
Language CoverageFull PHP 8.1+ language with zero syntax changes and zero subset restrictionsStatically typed PHP subset (binary builds use a main() entry point; extension mode compiles targeted classes)
Framework CompatibilityComplete drop-in for Laravel, Symfony, Shopware, WordPress, Pest, and PHPUnitBuilt for standalone native binaries or offloading hot classes into compiled .so extensions
LicenseMITGPL-3.0-only
Repository & Websitetypephp.dev · github.com/typephp-php/typephp · Packagistgithub.com/swoole/typephp
  • Choose typephp/typephp if you want an MIT-licensed, pure-PHP drop-in that enforces your existing PHPDoc contracts, reified generics, array shapes, and @self-out typestates across PHP 8.1+ applications and test suites without C++ toolchains or build steps.
  • Look at swoole/typephp if you are on PHP 8.4 or 8.5 and specifically want an AOT PHP-to-C++ compiler to produce standalone native executables or compiled .so extensions for CPU-heavy paths.

Rather than picking a single tool, most production PHP teams combine tools across layers:

GoalRecommended Stack
Maximum End-to-End Type SafetyPHPStan or Mago (offline CI/IDE) + TypePHP (Pest / PHPUnit suites & staging)
Strict API & Webhook BoundariesValinor or Framework Validator (HTTP ingress & 422 errors) + TypePHP (internal domain contracts & generics)
Legacy Codebase OnboardingPHPStan Baseline + TypePHP Audit Mode (on_violation => 'report') to uncover runtime DocBlock lies in 1 pass
Rich Domain ModelsTypePHP (structural types, shapes, reified generics, @self-out typestates) + webmozart/assert / beberlei/assert (business invariants like email/UUID/date comparisons)

Next Steps ​