Traits; parent & self type-hints in PHP 5.4

While this question is somewhat linguistic agnostic (agnostic for OOP languages ​​that support traits), I was involved in the nightly builds of PHP 5.4a and came across an odd script. It seems I can not start my installation, but this is another story.

Given the following snippet:

trait MyTrait { public function myMethod(self $object) { var_dump($object); } } class MyClass { use MyTrait; } $myObject = new MyClass(); $myObject->myMethod('foobar'); // <-- here 

What should happen? I would hope for an error indicating that $object should be an instance of MyClass .

When the trait methods are copied to the use -ing class, they are copied verbatim, how to resolve inheritance references to classes like these? Is this the intended functionality of Trait? (I did not work with another language that supported them)

+4
source share
2 answers

Well, I confirmed that this is actually, as I hoped and expected:

 class MyClass { use MyTrait; } $myObject = new MyClass(); $myObject->myMethod($myObject); // ok $myObject->myMethod('foobar'); // Catchable fatal error, argument must be instance etc 

So, good news for everyone.

+5
source

See RFC for more details: https://wiki.php.net/rfc/horizontalreuse

So yes, the intended behavior is that the attribute method behaves exactly the same as it would be defined in the class that uses it. Thus, references to the magic constant __CLASS__ resolved for the actual class name. If you ever need to know the name of a feature, you can use __TRAIT__ instead.

The goal is to make small related behavior multiple, and it comes from working in the Smalltalk world on Self and later Smalltalk directly. Other languages ​​with similar constructs are Perl6 and Scala. However, they have their own interpretation of the concept with usually different design attributes and intentions.

+4
source

All Articles