Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traits; parent & self type-hints in PHP 5.4

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)

like image 218
Dan Lugg Avatar asked Jan 19 '23 03:01

Dan Lugg


2 Answers

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.

like image 169
Dan Lugg Avatar answered Feb 02 '23 02:02

Dan Lugg


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.

like image 28
smarr Avatar answered Feb 02 '23 00:02

smarr