How can I create an instance of a class that has a private constructor

How can I create an instance of a class that has a private constructor.

I do not want to use any function inside the class to create my own instance.

Ex class:

class Test extends Test2 implements Test3 { private function __construct () { } function doDisplay() { } function Docall() { } } 
+6
source share
5 answers

You cannot create an instance of an object from a class whose constructor is private (from a program).

If you intend to use this function, you should have them as static and use them to meet your needs. Make sure the feature is publicly available.

For ex:

 <?php class something { private function __construct() { echo "something"; } public static function display($msg) { echo $msg; } } something::display("Testing..."); ?> 

See a working example: http://codepad.org/VoYeyk8W

+5
source

You cannot call a private constructor from anywhere except the class itself, so you need to use a static method that is accessible from the outside to create instances.

Also, if Test2 has a constructor that is not private, you cannot make Test::__construct() private.

+6
source

Whoever develops this class does not want you to instantiate directly, you cannot do what you want. Most likely, the original author had a good reason for this, maybe it was memory management, or he wanted to control the life cycle or stop problems with threads, there could be many reasons.

The only obvious answer is to rewrite the sources so that they work the way you want, instead of trying to get into someone else's design. Or you can create a wrapper around this class that hides the part you don't like, so you don’t need to know the rest of the code.

+1
source

You can initiate it with 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); 

This works, but keep in mind that this was not the use for which the class is intended, and that it may have some unforeseen side effects.

+1
source

Well, if you don't want to use the (static) method inside the class to instantiate, I think the answer to your question is simply this: you cannot.

0
source

Source: https://habr.com/ru/post/892100/


All Articles