Re: Traits and Properties
| From: | Patrick ALLAERT | Date: | Thu, 16 Dec 2010 21:05:24 +0000 |
| Subject: | Re: Traits and Properties | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-51062@lists.php.net to get a copy of this message | ||
2010/12/16 Stefan Marr <php@stefan-marr.de>:
> Hi:
>
> From my point of view the right thing to do with regard to properties is defined in the test
> cases below.
>
> The rational behind providing this semantics is based on the fact that PHP allows to define
> properties dynamically anyway, so there is no way around properties.
> However, there should be a way that a developer can notice that the code might not behave as
> expected in the composed class.
>
> It is true that behavior needs state to operate on, however, accessors are a common pattern and
> fully supported by traits. Furthermore, traits are not supposed to replace classes, and when a trait
> does more than just providing code that is to be easily reused, then the designed should ask the
> question whether that is not actually a class, which then provides the necessary guarantees to
> enforce the invariances the code expects.
>
> Thus, I would like to keep traits as a lightweight concept for code reuse..
>
> Best regards
> Stefan
>
> --TEST--
> Conflicting properties should result in a notice.
> Property use is discorage for traits that are supposed to enable maintainable
> code reuse. Accessor methods are the language supported idiom for this.
> --FILE--
> <?php
> error_reporting(E_ALL);
>
> trait THello1 {
> public $foo;
> }
>
> trait THello2 {
> private $foo;
> }
>
> class TraitsTest {
> use THello1;
> use THello2;
> }
>
> var_dump(property_exists('TraitsTest', 'foo'));
> ?>
> --EXPECTF--
> Notice: Trait THello1 and THello2 define the same property in the composition of TraitsTest.
> This might be incompatible, to improve maintainability consider using accessor methods instead.
> Class was composed in %s on line %d.
In this test, you might want to display some text before the
var_dump() (or alternatively to hardcode the line number on last line)
to ensure it is the property_exists() function call or the class
definition which would create such a notice.
Regards,
Patrick
--
Patrick Allaert
---
http://code.google.com/p/peclapm/ - Alternative PHP
Monitor