我正在尝试使用具有抽象类的已定义类的类。第一个类应实现一个接口,并且该接口使用抽象类描述方法。
我知道可以将Abstract Class用作Main Class中的参数,但是最好强制使用已定义的类。
<?php
interface TestInterface
{
function foo(): AbstractClass;
function bar(AbstractClass $par);
}
<?php
abstract class AbstractClass
{
private $foo;
private $bar;
public function getFoo()
{
return $this->foo;
}
public function setFoo($foo)
{
$this->foo = $foo;
return $this;
}
public function getBar()
{
return $this->bar;
}
public function setBar($bar)
{
$this->bar = $bar;
return $this;
}
}
<?php
class DefinedClass extends AbstractClass
{
private $foobar;
public function getFoobar()
{
return $this->foobar;
}
public function setFoobar($foobar)
{
$this->foobar = $foobar;
return $this;
}
}
<?php
class TestClass1 implements TestInterface
{
/** @var AbstractClass */
private $defined;
// Works
public function foo(): AbstractClass
{
return $this->defined;
}
// Works
public function bar(AbstractClass $defined)
{
$this->defined = $defined;
}
}
<?php
// Example 2
class TestClass2 implements TestInterface
{
/** @var DefinedClass */
private $defined;
// Doesnt work, class method and interface method not compatible
public function foo(): DefinedClass
{
return $this->defined;
}
// Doesnt work, class method and interface method not compatible
public function bar(DefinedClass $defined)
{
$this->defined = $defined;
}
}
我准备了一个例子。 TestClass1->一切都很好 TestClass2->抛出错误
Error on line 81:
Fatal error: Declaration of TestClass2::foo(): DefinedClass must be compatible with TestInterface::foo(): AbstractClass
是否可以或者必须将抽象类用作参数? (背景:学说/ Symfony实体生成使用已定义的类,并且使用此类更好。)