How can i instantiate a class which is having private constructor.?
I don't want to use any function inside the class to create its own instance.
Ex class is :
class Test extends Test2 implements Test3 {
private function __construct () {
}
function doDisplay() {
}
function Docall() {
}
}
You can instanciate it using Reflection (PHP >= 5.4)
class Test {
private $a;
private function __construct($a)
{
$this->a = $a;
}
}
$class = new ReflectionClass(Test::class);
$constructor = $class->getConstructor();
$constructor->setAccessible(true);
$object = $class->newInstanceWithoutConstructor();
$constructor->invoke($object, 1);
It works, but keep in mind that this was not an usage that the class was designed for, and that it might have some unforeseen side effects.
You can't invoke a private constructor from anywhere but within the class itself, so you have to use an externally-accessible static method to create instances.
Also, if Test2
has a constructor that isn't private, you can't make Test::__construct()
private.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With