Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP instanceof for traits

What is the proper way to check if a class uses a certain trait?

like image 418
xpedobearx Avatar asked Apr 09 '16 10:04

xpedobearx


People also ask

Can traits be inherited PHP?

In PHP, a trait is a way to enable developers to reuse methods of independent classes that exist in different inheritance hierarchies. Simply put, traits allow you to create desirable methods in a class setting, using the trait keyword. You can then inherit this class through the use keyword.

Can we instantiate trait in PHP?

A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own.

Can a trait have a constructor PHP?

Unlike traits in Scala, traits in PHP can have a constructor but it must be declared public (an error will be thrown if is private or protected). Anyway, be cautious when using constructors in traits, though, because it may lead to unintended collisions in the composing classes.

How do traits work in PHP?

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).


1 Answers

While nothing stops you from using methods to determine if a class uses a trait, the recommended approach is to pair traits with interfaces. So you'd have:

class Foo implements MyInterface {     use MyTrait; } 

Where MyTrait is an implementation of MyInterface.

Then you check for the interface instead of traits like so:

if ($foo instanceof MyInterface) {     ... } 

And you can also type hint, which you can't do with traits:

function bar(MyInterface $foo) {     ... } 

In case you absolutely need to know whether a class is using a certain trait or implementation, you can just add another method to the interface, which returns a different value based on the implementation.

like image 193
Kuba Birecki Avatar answered Oct 02 '22 11:10

Kuba Birecki