问题
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