PHP: Is it possible to get the name of the class using the trait from within a trait static method?

强颜欢笑 提交于 2020-01-04 03:06:28

问题


Can the name of a class using a trait be determined from within a static method belonging to that trait?

For example:

trait SomeAbility {
    public static function theClass(){
        return <name of class using the trait>;
    }
}

class SomeThing {
    use SomeAbility;
    ...
}

Get name of class:

$class_name = SomeThing::theClass();

My hunch is, probably not. I haven't been able to find anything that suggests otherwise.


回答1:


Use late static binding with static:

trait SomeAbility {
    public static function theClass(){
        return static::class;
    }
}

class SomeThing {
    use SomeAbility;
}

class SomeOtherThing {
    use SomeAbility;
}

var_dump(
    SomeThing::theClass(),
    SomeOtherThing::theClass()
);

// string(9) "SomeThing"
// string(14) "SomeOtherThing"

https://3v4l.org/mfKYM




回答2:


Yep, using the get_called_class()

<?php
trait SomeAbility {
    public static function theClass(){
        return get_called_class();
    }
}

class SomeThing {
    use SomeAbility;
}
// Prints "SomeThing"
echo SomeThing::theClass();



回答3:


You can call get_class() without a parameter to get the name of the current class...

trait SomeAbility {
    public static function theClass(){
        return get_class();
    }
}

class SomeThing {
    use SomeAbility;
}

echo SomeThing::theClass().PHP_EOL;


来源:https://stackoverflow.com/questions/50407466/php-is-it-possible-to-get-the-name-of-the-class-using-the-trait-from-within-a-t

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!