While this question is somewhat language agnostic (agnostic as far as OOP languages that support Traits) I've been tinkering with the nightly builds of PHP 5.4a, and came across an odd scenario. I can't seem to get my install to run anymore, but that's 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 $object
needs to be an instance of MyClass
.
When trait methods are copied into a use
-ing class, are they copied verbatim, as to resolve class inheritance references like these? Is this the intended functionality of a Trait? (I've not worked with another language that supported them)
Well, I've confirmed it is in fact as I had hoped for 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 all then.
Please see the RFC for more details: https://wiki.php.net/rfc/horizontalreuse
So, yes indeed, the intended behavior is that the method of the trait behaves exactly as it would have been defined in the class that uses it.
Thus, also references to the magic __CLASS__
constant are resolved to the actual class name.
If you how ever need to know the name of the trait you could use __TRAIT__
instead.
The goal is to make small related behavior reusable and it origins from the work in the Smalltalk world on Self and later Smalltalk directly. Other languages having similar constructs are Perl6 and Scala. However, they have their very own interpretation of the concept with usually different properties and design intents.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With