Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP type-hinting traits

I have a trait. For the sake of creativity, let's call this trait Trait:

trait Trait{         static function treat($instance){             // treat that trait instance with care     } } 

Now, I also have a class that uses this trait, User. When trying to call treat with an instance of User, everything works. But I would like to type-hint that only instances of classes using Trait should be given as arguments, like that:

static function treat(Trait $instance){...} 

Sadly, though, this results in a fatal error that says the function was expecting an instance of Trait, but an instance of User was given. That type of type-hinting works perfectly for inheritance and implementation, but how do I type-hint a trait?

like image 265
arik Avatar asked Jan 04 '13 12:01

arik


People also ask

What is PHP type hinting?

Type hinting is a concept that provides hints to function for the expected data type of arguments. For example, If we want to add an integer while writing the add function, we had mentioned the data type (integer in this case) of the parameter.

Should I use type hinting in PHP?

Apparently 'type hinting' in PHP can be defined as follows: "Type hinting" forces you to only pass objects of a particular type. This prevents you from passing incompatible values, and creates a standard if you're working with a team etc.

Which data types can be declared with type hinting in PHP?

In simple word, type hinting means providing hints to function to only accept the given data type. In technical word we can say that Type Hinting is method by which we can force function to accept the desired data type. In PHP, we can use type hinting for Object, Array and callable data type.

What are traits 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).


2 Answers

You can't as DaveRandom says. And you shouldn't. You probably want to implement an interface and typehint on that. You can then implement that interface using a trait.

like image 105
Veda Avatar answered Sep 22 '22 05:09

Veda


For people ending up here in the future, I would like to elaborate on Veda's answer.

  1. It's true that you can't treat traits as traits in PHP (ironically), saying that you expect an object that has some traits is only possible via interfaces (essentially a collection of abstract traits)
  2. Other languages (such as Rust) actually encourage type hinting with traits

In conclusion; your idea is not a crazy one! It actually makes a lot of sense to view traits as what they are in the common sense of the word, and other languages do this. PHP seems to be stuck in the middle between interfaces and traits for some reason.

like image 26
Tristan Godfrey Avatar answered Sep 22 '22 05:09

Tristan Godfrey