Skip to content

Instantly share code, notes, and snippets.

@lastguest
Last active September 7, 2018 12:58
Show Gist options
  • Save lastguest/736c24f11a627021682a5d7bb5cb433f to your computer and use it in GitHub Desktop.
Save lastguest/736c24f11a627021682a5d7bb5cb433f to your computer and use it in GitHub Desktop.
[PHP] Pull namespace prefix into global scope
<?php
function using($ns) {
static $ns_cache = [];
$ns = trim($ns, '\\');
if (empty($ns_cache[$ns])) {
return spl_autoload_register($ns_cache[$ns] = function($class) use ($ns) {
return class_exists("$ns\\$class", false) && class_alias("$ns\\$class", $class, true);
}, true, false);
} else return false;
}
/* ***************
* EXAMPLE
* ***************
namespace Foo\Bar {
class Baz {
public static function lol(){
echo "kek";
}
}
}
namespace {
using("Foo\\Bar");
Baz::lol();
}
// kek
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment