<?php /** * Can I create an alias for an entire namespace in PHP? * * class_alias() on spl_autoload_class() for namespace prefix * * @link https://stackoverflow.com/a/74236530/367456 * @author hakre <https://hakre.wordpress.com/> */ namespace { // warning instead of exception to simulate testing mode on 3v4l.org, // in development it should throw so that code touching path is // updated. ini_set('assert.exception', '0'); spl_autoload_register( static function (string $class_name) { static $old = 'My\\Old\\Lib\\Name\\'; static $new = 'My\\Tiger\\Lib\\Name\\'; // only operate on the old namespace if (0 !== strpos($class_name, $old)) { return; } $new_name = str_replace($old, $new, $class_name); assert(false, "old namespace in use: $class_name"); class_alias($new_name, $class_name); $exists = class_exists($new_name); assert($exists, "aliasing old namespace failed for class: $class_name"); }, $throw = true, /* throw when registering fails */ $prepend = false /* only alias at fall-through */ ); } namespace My\Tiger\Lib\Name\Module { class Boring { } } namespace My\Old\Lib\Name { use My\Old\Lib\Name\Module\Boring; $boring = new Boring(); assert($boring); assert($boring instanceof Module\Boring); var_dump(get_class($boring)); }
You have javascript disabled. You will not be able to edit any code.