How do I get an object's unqualified (short) c

2019-01-30 07:15发布

How do I check the class of an object within the PHP name spaced environment without specifying the full namespaced class.

For example suppose I had an object library/Entity/Contract/Name.

The following code does not work as get_class returns the full namespaced class.

If(get_class($object) == 'Name') {
... do this ...
}

The namespace magic keyword returns the current namespace, which is no use if the tested object has another namespace.

I could simply specify the full classname with namespaces, but this seems to lock in the structure of the code. Also not of much use if I wanted to change the namespace dynamically.

Can anyone think of an efficient way to do this. I guess one option is regex.

20条回答
看我几分像从前
2楼-- · 2019-01-30 08:00

Yii way

\yii\helpers\StringHelper::basename(get_class($model));

Yii uses this method in its Gii code generator

Method documentation

This method is similar to the php function basename() except that it will treat both \ and / as directory separators, independent of the operating system. This method was mainly created to work on php namespaces. When working with real file paths, php's basename() should work fine for you. Note: this method is not aware of the actual filesystem, or path components such as "..".

More information:

https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseStringHelper.php http://www.yiiframework.com/doc-2.0/yii-helpers-basestringhelper.html#basename()-detail

查看更多
Root(大扎)
3楼-- · 2019-01-30 08:01

Based on @MaBi 's answer, I made this:

trait ClassShortNameTrait
{
    public static function getClassShortName()
    {
        if ($pos = strrchr(static::class, '\\')) {
            return substr($pos, 1);
        } else {
            return static::class;
        }
    }
}

Which you may use like that:

namespace Foo\Bar\Baz;

class A
{
    use ClassShortNameTrait;
}

A::class returns Foo\Bar\Baz\A, but A::getClassShortName() returns A.

Works for PHP >= 5.5.

查看更多
登录 后发表回答