Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i instantiate a class which is having private constructor

Tags:

php

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() {
   }
}
like image 861
Sahal Avatar asked Jul 06 '11 05:07

Sahal


2 Answers

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.

like image 90
Lulhum Avatar answered Oct 05 '22 22:10

Lulhum


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.

like image 41
BoltClock Avatar answered Oct 05 '22 23:10

BoltClock