christophrumpel/method-overrider

A PHP package to override methods.

v1.3.0 2024-11-10 12:51 UTC

This package is auto-updated.

Last update: 2025-09-30 14:44:46 UTC


README

GitHub Workflow Status (master) Total Downloads Latest Version License

PHP Method Overrider

⚠️ Experimental Package - This is a work in progress and not intended for production use.

Dynamically override specific methods of any PHP class at runtime while preserving method signatures and providing access to the original implementation.

Installation

composer require christophrumpel/method-overrider

Usage

use ChristophRumpel\MethodOverrider\MethodOverrider;

class MathService
{
    public function add(int $a, int $b): int
    {
        return $a + $b;
    }
}

$overrider = new MethodOverrider();

// Override the add method to multiply instead
$instance = $overrider->override(
    class: MathService::class,
    methodNames: 'add',
    implementations: function (callable $original, int $a, int $b): int {
        // You can still call the original method
        $originalResult = $original();

        // Or implement completely new logic
        return $a * $b;
    }
);

echo $instance->add(2, 3); // Output: 6 (multiplied instead of added)

How it works

The package uses reflection to analyze method signatures and dynamically generates new classes that extend your original class. The overridden methods wrap your custom implementations while providing access to the original method via a closure.

Requirements

  • PHP 8.3+