php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #55613 Feature: Trait checks type of consuming class
Submitted: 2011-09-06 01:10 UTC Modified: 2011-11-18 14:00 UTC
Votes:1
Avg. Score:4.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:0 (0.0%)
From: wil dot moore at wimoore dot com Assigned:
Status: Suspended Package: Class/Object related
PHP Version: 5.4.0alpha3 OS: Mac (Darwin 10.8.0 i386)
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: wil dot moore at wimoore dot com
New email:
PHP Version: OS:

 

 [2011-09-06 01:10 UTC] wil dot moore at wimoore dot com
Description:
------------
For instance, one may require that the use of a trait "requires" that the 
consuming class must be of a certain type or implement a specific interface.

An example is Doctrine2's ArrayCollection. One may want to write a utility trait 
that mixes in functionality that is useful to this type of Collection. This trait 
would work with ArrayCollections or its decedents but would throw an Exception 
(i.e. TraitConsumerIllegalTypeException) if attempting to use with other types of 
classes.





Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2011-09-12 10:54 UTC] gron@php.net
So far the community was opposed to 'requiring' interfaces from using classes.
However, you can always express 'require' relationships to individual methods by 
adding them as abstract methods to the trait.

From my point of view that is also the way to go, since traits do not preserve your 
invariants, and are meant for code reuse only. Thus, if you imply a certain 
invariants with an interface, that is not enforced by a trait.
A trait can require a certain method to be available since it will be using it, and 
you might want that to be check at compile time, but a trait does not promise to 
obey a certain set of requirements on invariants.

Please consider using composition and classes if you have strong requirements on how 
to interact with an object.
 [2011-11-18 14:00 UTC] gron@php.net
-Status: Open +Status: Suspended
 [2011-11-18 14:00 UTC] gron@php.net
I will close this for now.
The RFC already stated a possible solution for such a feature: 
https://wiki.php.net/rfc/horizontalreuse#requiring_composing_class_to_implement_in
terface

We might reconsider this for a the next release after 5.4, I think.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Mon Oct 14 18:01:28 2024 UTC