例如,有这样一种情况。
interface ITest
{
public function test();
}
class Test implements ITest
{
...
}
interface ITest2 extends ITest
{
public function test($a = '');
}
class Test2 extends Test implements ITest2
{
...
}
class WorkWithTest
{
protected ITest $var;
public function __construct($test)
{
$this->var = $test;
}
}
class WorkWithTest2 extends WorkWithTest
{
protected ITest2 $var; //PHP Fatal error: Type of WorkWithTest2::$var must be ITest
public function __construct($test2)
{
$this->var = $test2;
}
}
如何创建一个类WorkWithTest2
以使其仅适用于实现 ITest2 接口的实例?
将属性设为私有:
您的问题是您正在使用继承,但是,这没有任何意义,它只会阻碍您。
如果您没有在继承上下文中正确使用属性,那么您根本不需要继承它。