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
| Tool | Category | When It Runs | Uses Existing PHPDocs? | Reified Generics in RAM | Catches Dynamic Data (DB / JSON / DI) | Standard PHP 8.1+ Drop-In |
|---|---|---|---|---|---|---|
TypePHP (typephp/typephp) | Runtime Type Checker | Runtime (LTW / OPcache) | Yes (zero boilerplate) | Yes (\WeakMap) | Yes | Yes |
| PHPStan | Static Analyzer | Offline / CI / IDE | Yes | No (compile-time only) | No | Yes |
| Psalm | Static Analyzer | Offline / CI / IDE | Yes | No (compile-time only) | No | Yes |
| Phan | Static Analyzer | Offline / CI | Yes | No (compile-time only) | No | Yes |
| Mago | Static Analyzer / Toolchain | Offline / CI / IDE | Yes | No (compile-time only) | No | Yes |
beberlei/assert | Assertion Library | Runtime | No (manual calls) | No | Yes (where written) | Yes |
webmozart/assert | Assertion Library | Runtime | No (manual calls) | No | Yes (where written) | Yes |
Native assert() | Language Construct | Runtime (dev only) | No (manual calls) | No | Yes (where written) | Yes |
cuyz/valinor | Object Mapper / Hydrator | Runtime (at map()) | Yes (DTO hydration) | No (validates on map) | Yes (at map boundary) | Yes |
azjezz/psl (Psl\Type) | Runtime Type Combinators | Runtime | No (explicit schemas) | No | Yes (where called) | Yes |
Swoole TypePHP (swoole/typephp) | AOT PHP-to-C++ Compiler | Build-Time -> Native Binary | Subset / Typed PHP | C++ Containers | Compile-time subset | No (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
objectormixedmiddleware, or mutated through shared variable aliases ($shared = $session; $session->login();). - Runtime Generic State: Guaranteeing a
Collection<User>cannot be polluted with aProductdownstream 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:
<?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:
// 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:
<?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
| Criterion | TypePHP | beberlei/assert / webmozart/assert | Native PHP assert() |
|---|---|---|---|
Type Contracts (list<T>, shapes, generics) | Automatic from PHPDocs | Manual calls per parameter | Manual boolean expressions |
Domain Business Invariants (e.g. email, UUID, $end > $start, file exists) | Not a business validator | Excels here | Manual expressions |
| Return, Property & Interface Inheritance | Automatic across hierarchies | Must be repeated in every implementation | Must be repeated manually |
Reified Generics (Collection<User>) | Native via \WeakMap | Not supported | Not supported |
1-Pass Audit Mode (report) | Built-in JSON audit & sharding | Throws on first failure | Throws / warns on failure |
| Zero-Cost Production Toggle | TYPEPHP_DISABLE=true / enabled => false | Always executes in prod | Zero 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\Typediffers from TypePHP:Psl\Typerequires you to explicitly build type schema objects and callassert()orcoerce()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\WeakMapgenerics, typestates (@self-out), and compile-time AST check elimination. - Where
Psl\Typestill shines: Unlike TypePHP, which strictly validates values without modifying them,Psl\Typealso supports explicit type coercion (such as safely coercing'42'from HTTP query strings intoint), 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 Architecture | Pure-PHP runtime type checker using Load-Time Weaving (file:// StreamWrapper) and \WeakMap reification | Ahead-of-Time (AOT) compiler (tpc.php / tpc) translating a typed PHP subset into C++17 and native machine code |
| Primary Goal | Eradicate DocBlock lies and bring true reified generics and typestates to standard PHP codebases | Compile CPU-bound PHP code into standalone native executables, PHP extensions (.so), or shared libraries |
| PHP Version Requirement | PHP 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 Tools | composer require --dev typephp/typephp with zero system dependencies | composer 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 Target | Standard Zend Engine (PHP-FPM, CLI, FrankenPHP, RoadRunner, Swoole, WASM) | Compiled C++17 native binaries or loaded Zend extensions (extension=...) |
| Language Coverage | Full PHP 8.1+ language with zero syntax changes and zero subset restrictions | Statically typed PHP subset (binary builds use a main() entry point; extension mode compiles targeted classes) |
| Framework Compatibility | Complete drop-in for Laravel, Symfony, Shopware, WordPress, Pest, and PHPUnit | Built for standalone native binaries or offloading hot classes into compiled .so extensions |
| License | MIT | GPL-3.0-only |
| Repository & Website | typephp.dev · github.com/typephp-php/typephp · Packagist | github.com/swoole/typephp |
- Choose
typephp/typephpif you want an MIT-licensed, pure-PHP drop-in that enforces your existing PHPDoc contracts, reified generics, array shapes, and@self-outtypestates across PHP 8.1+ applications and test suites without C++ toolchains or build steps. - Look at
swoole/typephpif 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.soextensions for CPU-heavy paths.
5. Recommended Combinations
Rather than picking a single tool, most production PHP teams combine tools across layers:
| Goal | Recommended Stack |
|---|---|
| Maximum End-to-End Type Safety | PHPStan or Mago (offline CI/IDE) + TypePHP (Pest / PHPUnit suites & staging) |
| Strict API & Webhook Boundaries | Valinor or Framework Validator (HTTP ingress & 422 errors) + TypePHP (internal domain contracts & generics) |
| Legacy Codebase Onboarding | PHPStan Baseline + TypePHP Audit Mode (on_violation => 'report') to uncover runtime DocBlock lies in 1 pass |
| Rich Domain Models | TypePHP (structural types, shapes, reified generics, @self-out typestates) + webmozart/assert / beberlei/assert (business invariants like email/UUID/date comparisons) |
Next Steps
- Ready to test TypePHP in your own test suite? Follow the Installation Guide.
- Want to audit an existing codebase without crashing on the first mismatch? Read Violation Reporting & Auditing.
- Curious how TypePHP stays fast (~1.2% overhead on Laravel, 3.5M+ ops/sec with JIT)? See Compile-Time Check Elimination and Performance Considerations.