Mikhail Stroev
Mikhail Stroev

Reputation: 105

PHP Traits for interfaces

I have the next code

<?php

interface SimpleInterface
{
    public function method(): self;
}

trait SimpleTrait
{
    public function method(): self
    {
        return $this;
    }
}

class SomeClass implements SimpleInterface
{

    use SimpleTrait;
}

But PHP says that RenderableTrait->setLayout(layout:string) isn't compatible with RenderableInterface->setLayout(layout: string)

Obviously, because interface expects self as returned value, but in trait I return Trait itself and it's not compatible. Are there any solutions?

Upvotes: 0

Views: 1646

Answers (1)

Eakethet
Eakethet

Reputation: 682

Change you return type self for SimpleInterface https://3v4l.org/LTc8E

<?php

trait Test {
    public function test() {
        return $this;
    }
}

class Foo {
    use Test;
}

class Bar {
    use Test;
}

$f = new Foo();
$b = new Bar();
// object(Foo)
var_dump($f->test());
// object(Bar)
var_dump($b->test());

//So for you case
interface SimpleInterface
{
    public function method(): SimpleInterface;
}

trait SimpleTrait
{
    // This method will work only in classes that implements SimpleInterface
    public function method(): SimpleInterface
    {
        return $this;
    }
}

class SomeClass implements SimpleInterface
{
    // Traits $this is now SomeClass
    use SimpleTrait;
}

$s = new SomeClass();
// object(SomeClass)
var_dump($s->method());

Upvotes: 1

Related Questions