Search by

aclips / class-override

aclips

Runtime PHP class overriding with inheritance

Package info

github.com/aclips/class-override

pkg:composer/aclips/class-override

Statistics

Installs: 6

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.0.2 2026-11-26 13:35 UTC

This package is auto-updated.

Last update: 2026-11-26 13:36:41 UTC


README

Runtime PHP class overriding with inheritance.

aclips/class-override lets you replace a named class from a third-party package with your own descendant without modifying the package sources. The library prepares a virtual copy of the original class, points your class at it, loads your class and registers it under the original name with class_alias(). Existing code keeps working with the original name, while new OriginalName() creates your object and parent::method() calls the original implementation.

Requirements

  • PHP ^8.1
  • Composer
  • nikic/php-parser ^5.0 (installed automatically as a dependency)
  • Readable source files for the original and override classes; the paths are given in the configuration, so framework autoloaders (Bitrix, legacy kernels) work without Composer class resolution
  • The library must be initialized before the first access to any overridden class

Installation

composer require aclips/class-override

Configuration

Configuration is a PHP file that returns an array. The key is the fully qualified name of the original class. original_class_path is the path to the file declaring the original class, override_class_path is the path to the file declaring your class, replace is an optional map of method visibility changes for the original class.

<?php

return [
    \Vendor\Package\SomeClass::class => [
        'original_class_path' => __DIR__ . '/../vendor/vendor/package/src/SomeClass.php',
        'override_class_path' => __DIR__ . '/../src/Override/SomeClass.php',
    ],

    \Vendor\Package\AnotherClass::class => [
        'original_class_path' => __DIR__ . '/../vendor/vendor/package/src/AnotherClass.php',
        'override_class_path' => __DIR__ . '/../src/Override/AnotherClass.php',
        'replace' => [
            'someMethod' => [
                'visibility' => 'public',
            ],
        ],
    ],
];

The override class is discovered from override_class_path: the file must contain exactly one class extending the original class. Both paths are validated during init(), together with the presence of the original class in its file.

A framework class that is not registered with Composer can be overridden the same way:

<?php

return [
    \CCrmDeal::class => [
        'original_class_path' => __DIR__ . '/../../bitrix/modules/crm/classes/mysql/crm_deal.php',
        'override_class_path' => __DIR__ . '/../../local/override/crm_deal.php',
        'replace' => [],
    ],
];

Allowed visibility values: public, protected, private.

Override class

Your class extends the original class as usual:

<?php

namespace App\Override;

class SomeClass extends \Vendor\Package\SomeClass
{
    public function someMethod(): string
    {
        return 'custom';
    }
}

Initialization

Initialize the library once after loading Composer autoload and before the first access to any overridden class:

<?php

require_once __DIR__ . '/vendor/autoload.php';

\Aclips\ClassOverride\Override::init(
    __DIR__ . '/config/override.php'
);

PHP cannot replace a class that is already declared, so initialization after the original class has been loaded throws an OverrideException. The same applies when the original class is already declared at the moment of init(). init() also validates the configured paths: the original class must be found in original_class_path, and override_class_path must contain a class extending it. Initialize first, then use the classes.

Calling init() twice with the same configuration is a no-op. Calling it again with a different configuration throws an OverrideException.

Replace

replace changes the visibility of methods on the original class. This is useful when you need to call or override a method that is protected or private in the original class.

<?php

return [
    \Vendor\Package\SomeClass::class => [
        'original_class_path' => __DIR__ . '/../vendor/vendor/package/src/SomeClass.php',
        'override_class_path' => __DIR__ . '/../src/Override/SomeClass.php',
        'replace' => [
            'someMethod' => [
                'visibility' => 'public',
            ],
        ],
    ],
];

Behavior of replace:

  • method names are matched case-insensitively;
  • a missing method, an unknown key or an invalid visibility value throws an OverrideException;
  • only methods declared directly in the class are visible to replace: methods coming from traits or parent classes cannot be changed, and the error message says so;
  • changing visibility does not remove final: changing the visibility of a final method throws an OverrideException, because the method still cannot be overridden;
  • replace only changes visibility, it never changes the method body;
  • static and abstract modifiers are preserved.

Limitations and known features

  • Already declared classes cannot be replaced. init() and the loader throw an OverrideException instead of silently doing nothing.
  • final classes and final methods cannot be overridden.
  • Interfaces, traits and enums cannot be overridden.
  • Classes provided by PHP extensions cannot be overridden.
  • The configured source paths are used as given: no Composer class resolution is needed for the overridden classes themselves. Composer ClassLoader instances registered in spl_autoload_functions() are used only to intercept other classes that share a source file with a configured class. Without such a loader (framework autoloaders), those sibling classes must be loaded before initialization or live in separate files.
  • The override class is discovered by parsing override_class_path: exactly one class in that file must extend the original class, otherwise init() throws an OverrideException.
  • Classes loaded with a direct require before initialization are not handled.
  • Method bodies cannot be replaced through configuration, only visibility.
  • A class that extends an overridden class must not be declared in the same source file as the class it extends (including anonymous classes and subclasses of the override class itself). Such a configuration throws an OverrideException naming both classes; move the subclass to a separate file. Chained overrides in separate files work as usual.
  • Classes that share a source file with a configured class are loaded from a sanitized copy of that file, in which the configured classes are renamed. This keeps the original declaration semantics and avoids redeclare errors.
  • Inside the overridden original class, self::class and __CLASS__ return the internal virtual class name, not the original name. static:: binds to your class, exactly as with normal inheritance. new self() creates an instance of the virtual class. The same applies to __METHOD__: it returns the virtual class name, and __LINE__ refers to the generated file. __FILE__ and __DIR__ are rewritten to the original source location and keep their usual meaning.
  • Top-level executable code in an overridden source file must not trigger the loading of a class that is declared later in the same file. If the generated file fails during loading, the failure is reported once and the file is not retried in the same process.
  • Requiring the override class file directly after initialization is not supported.
  • Generated files are cached in sys_get_temp_dir()/aclips-class-override-<uid>. The cache key includes the source path and content hash, the configured class names and replace settings, and the versions of the compiler, PHP and nikic/php-parser. Changing any of them regenerates the file. Files and directory ownership are verified before loading, because the temporary directory is shared. Cached files are not garbage collected and may accumulate over time.

Full minimal example

Layout:

project/
├── composer.json
├── config/
│   └── override.php
├── src/
│   ├── Override/
│   │   └── SomeClass.php
│   └── ...
└── vendor/

composer.json:

{
    "require": {
        "aclips/class-override": "^1.0"
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}

config/override.php:

<?php

return [
    \Vendor\Package\SomeClass::class => [
        'original_class_path' => __DIR__ . '/../vendor/vendor/package/src/SomeClass.php',
        'override_class_path' => __DIR__ . '/../src/Override/SomeClass.php',
    ],
];

src/Override/SomeClass.php:

<?php

namespace App\Override;

class SomeClass extends \Vendor\Package\SomeClass
{
    public function someMethod(): string
    {
        return 'custom:' . parent::someMethod();
    }
}

Bootstrap:

<?php

require_once __DIR__ . '/vendor/autoload.php';

\Aclips\ClassOverride\Override::init(__DIR__ . '/config/override.php');

$object = new \Vendor\Package\SomeClass();

var_dump($object instanceof \App\Override\SomeClass); // true
echo $object->someMethod();                          // your implementation

Tests

composer test