views:

107

answers:

3
+1  Q: 

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?

+4  A: 

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)

philfreo
Good additional explanation.
jheddings
Up-votes are appreciated :)
philfreo
would I still need the __construct ?
Daniel
I think you have this the wrong way around. The constructor should be called __construct(), unless you need to support PHP4. __construct is newer.
Tom Haigh
(I think that's what he meant)anyway, I realized why you had the constructor private, but I find I can do all that stuff in the factory. That way I can use the constructor if I need.
Daniel
I edited my answer - you guys are right, my note about __construct() was mixed up.
philfreo
+1  A: 

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);
}
jheddings
I beat you by 3 seconds :)
philfreo
Great minds... :)
jheddings
and I believe that your create method should be a static method, like in my solution.
philfreo
IIRC, PHP will still recognize the call, but putting static is more explicit and ensures no '$this' pointer.
jheddings
A: 

I believe you are correct. A print_r of your new object will show it returns an object.

You could make it throw an exception, but that's unlikely to be the style you want.

+1 on factory methods already posted. Those factory methods might also be like:

public static function newCreate( $a ) { return ( !$a ) ? false : new foo( $a ); }

I like factory methods :-)

memnoch_proxy