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.
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
}
}