今天我回忆起两年前接受采访的问题.
我想解决它,因为它非常困扰我.
所以,这是我的PHP类:
class A
{
function __construct(A $aObject)
{
$aObject->getValue();
return;
}
function getValue()
{
echo 'Success';
}
}
Run Code Online (Sandbox Code Playgroud)
我怎么能创建这个类的对象?但我们无法改变这门课程.
有多种解决方案,最简单的解决方案是使用ReflectionClass::newInstanceWithoutConstructor:
$a = new A((new ReflectionClass("A"))->newInstanceWithoutConstructor());
Run Code Online (Sandbox Code Playgroud)
另一个解决方案是扩展类并在那里重载构造函数:
class B extends A {
function __construct() {}
}
$a = new A(new B);
Run Code Online (Sandbox Code Playgroud)