Php – In PHP, is it possible to create an instance of an class without calling class’s constructor

oopPHP

By any means, is it possible to create an instance of an php class without calling its constructor ?

I have Class A and while creating an instance of it am passing file and in constructor of Class A am opening the file.

Now in Class A, there is function which I need to call but am not required to pass file and so there is not need to use constructor functionality of opening file as am not passing file.

So my question is, Is it possible by any means to create an instance of an PHP class without calling its constructor ?

Note I cannot make function static as am using some of the class properties in function.

Best Answer

In your case I would recommend to think about redesigning your code so you don't need to do such a things, but to answer you question: yes, it is possible.

You can use ReflectionClass and it's method newInstanceWithoutConstructor introduced in PHP 5.4 Then it's very easy to create an instance of a class without calling its constructor:

$reflection = new ReflectionClass("ClassName");
$instance = $reflection->newInstanceWithoutConstructor(); //That's it!