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.
A trait is similar to a class, but it is only for grouping methods in a fine-grained and consistent way. PHP does not allow you to create an instance of a Trait like an instance of a class. And there is no such concept of an instance of a trait.
Naming conventions for code released by PHP FIG¶ Interfaces MUST be suffixed by Interface : e.g. Psr\Foo\BarInterface . Abstract classes MUST be prefixed by Abstract : e.g. Psr\Foo\AbstractBar . Traits MUST be suffixed by Trait : e.g. Psr\Foo\BarTrait . PSR-1, 4, and 12 MUST be followed.
Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected).
The main difference between the Traits and Interfaces in PHP is that the Traits define the actual implementation of each method within each class, so many classes implement the same interface but having different behavior, while traits are just chunks of code injected in a class in PHP.
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
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With