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.