Check is alias:
<?php
/**
* @param string $class Class name
* @return bool
*/
function is_alias(string $class): bool
{
return $class !== (new ReflectionClass($class))->name;
}
?>
Get class aliases:
<?php
/**
* @param string $class Class name
* @param bool $throw Throw exception at error?
* @return string[]|null Aliases or null at error in silent mode
* @throws InvalidArgumentException Class not exists or it's alias
*/
function get_class_aliases(string $class, bool $throw = false): ?array
{
/**
* @var array An array of defined classes: keys - classes, values - aliases
*/
static $classes = [];
// check: class exists
if (! class_exists($class, true)) {
if ($throw) {
throw new InvalidArgumentException('Class ' . $class . ' not exists');
}
return null;
}
// refresh list
$newClasses = array_diff(get_declared_classes(), array_keys($classes));
if ($newClasses) {
$abc = range('a', 'z');
foreach ($newClasses as $newClass) {
// fast check first char: class_alias() convert alias to lower case
if (in_array($newClass[0], $abc, true)) {
$realClass = (new ReflectionClass($newClass))->getName();
$classes[$newClass] = $newClass !== $realClass ? $realClass : null;
} else {
$classes[$newClass] = null;
}
}
unset($abc, $newClasses);
}
// check: is alias?
if (! empty($classes[$class])) {
if ($throw) {
throw new InvalidArgumentException($class . ' is alias for class ' . $classes[$class]);
}
return null;
}
// find aliases
return array_keys($classes, $class, true);
}
?>
Usage:
<?php
class Foo {}
class_alias('Foo', 'Bar');
class_alias('Bar', 'Baz');
$aliases = get_class_aliases('Foo', true); // ['bar', 'baz']
?>