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.
In PHP you can create objects w/o calling the constructor. But that does not work by using new but by un-serializing an object instance. The constructor can then be called manually.
You are not required to define a constructor in your class, but if you wish to pass any parameters on object construction then you need one.
To create an instance of a class, the new keyword must be used. An object will always be created unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).
The constructor of the child class doesn't automatically call the constructor of its parent class. Use parent::__construct(arguments) to call the parent constructor from the constructor in the child class.
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!
A classes constructor will always be called. There are a couple ways you could work around this, though.
The first way is to provide default values for your parameters in the constructor, and only perform certain actions on those parameters if they're set. For example:
class MyClass {
public __construct($file = null) {
if ($file) {
// perform whatever actions need to be done when $file IS set
} else {
// perform whatever actions need to be done when $file IS NOT set
}
// perform whatever actions need to be done regardless of $file being set
}
}
Another option is to extend your class such that the constructor of the child class does not call the constructor of the parent class.
class MyParentClass {
public __construct($file) {
// perform whatever actions need to be done regardless of $file being set
}
}
class MyChildClass extends MyParentClass {
public __construct() {
// perform whatever actions need to be done when $file IS NOT set
}
}
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