3v4l.org

run code in 300+ PHP versions simultaneously
<?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)); }
Output for 8.3.0 - 8.3.26, 8.4.1 - 8.4.14
Deprecated: ini_set(): assert.exception INI setting is deprecated in /in/k2SDE on line 16 Warning: assert(): old namespace in use: My\Old\Lib\Name\Module\Boring failed in /in/k2SDE on line 28 string(31) "My\Tiger\Lib\Name\Module\Boring"
Output for 7.2.34, 7.3.0, 7.4.0 - 7.4.33, 8.0.1 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29
Warning: assert(): old namespace in use: My\Old\Lib\Name\Module\Boring failed in /in/k2SDE on line 28 string(31) "My\Tiger\Lib\Name\Module\Boring"

preferences:
129.73 ms | 408 KiB | 5 Q