我有下一个代码
<?php
interface SimpleInterface
{
public function method(): self;
}
trait SimpleTrait
{
public function method(): self
{
return $this;
}
}
class SomeClass implements SimpleInterface
{
use SimpleTrait;
}
但是PHP指出RenderableTrait->setLayout(layout:string)
与RenderableInterface->setLayout(layout: string)
不兼容
显然,因为接口期望self作为返回值,但是在特征中我返回Trait本身,并且它不兼容。有什么解决办法吗?
答案 0 :(得分:0)
更改返回类型为 SimpleInterface 的 self 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());