Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php constructors

public function __construct($input = null) {
    if (empty($input)){
        return false;
    }

and then there's some constructor code...

what I would like to do is for the class to not initialize if I pass an empty variable

$classinstance = new myClass(); I want $classinstance to be empty (or false)

I think this is not possible like this, What's an easy way to accomplish a similar result?

like image 362
Daniel Avatar asked Nov 26 '25 01:11

Daniel


2 Answers

You could make private the normal constructor (so it can't be used from outside the object, like you would if you were making a Singleton) and create a Factory Method.

class MyClass {
    private function __construct($input) {
        // do normal stuff here
    }
    public static function factory($input = null) {
        if (empty($input)){
            return null;
        } else {
            return new MyClass($input);
        }
    }
}

Then you would instantiate a class like this:

$myClass = MyClass::factory($theInput);

(EDIT: now assuming you're only trying to support PHP5)

like image 115
philfreo Avatar answered Nov 27 '25 15:11

philfreo


You could use a factory method to create the object:

private function __construct($input = null) {
}

public static function create($input = null) {
    if (empty($input)) {
        return false;
    }
    return new MyObject($input);
}    
like image 26
jheddings Avatar answered Nov 27 '25 15:11

jheddings



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!