开发者

How can i instantiate a class which is having private constructor

How can i instantiate a class whi开发者_StackOverflow社区ch 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.


You cannot instantiate an object from a class whose constructor is private (out of syllabus).

If you are intend to use it's function, then you should have them as static and use them to fulfill your needs. Make sure that function is public.

For ex:

<?php

class something
{
    private function __construct()
    {
        echo "something";
    }

    public static function display($msg)
    {
        echo $msg;
    }
}

something::display("Testing...");

?>

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


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

The only obvious answer is to rewrite the sources so they work the way you want instead of trying to break into someone else's design. Or you could build a wrapper around this class that hides away the part you don't like so the rest of you code doesn't have to know.


Well, if you don't want to use a (static) method inside the class to create an instance I guess the answer to your question simply is: you cannot.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜