Jazzpaths
Jazzpaths

Reputation: 709

Can I exit (return) prematurely from a Class constructor?

I need to exit prematurely from a class constructor if one of the arguments in the constructor satisfy a certain condition, can I just use return as in the example below or there's another way to do that?

class Test {

  public function __construct( arg1, arg 2 ) {

    switch case( arg2 ) {
      case 'case1':
        ...do some settings for the code to follow...
      break;
      case 'case2':
        return; // Can I do this?
      break;
    }

    ...Other code to execute if args2 wasn't 'case2'...

  }

}

Thanks to everyone who'll answer.

Edit

For anyone who could find the question weird: in some languages a constructor should return specific values in order to actually create a class, that's why I'm asking.

Upvotes: 0

Views: 702

Answers (1)

deceze
deceze

Reputation: 522135

__construct is just a normal function invoked by a normal function call, and yes, you can return from that function at any time as you can with any other function too. Note that whatever value you return from __construct will be ignored, but that's apparently of no concern here.

For that reason (that __construct doesn't return anything), I'd refrain from a premature exit for readability reasons, but there's no technical reason to. I'd rather prefer an if-this-do-that pattern than an if-this-stop-prematurely pattern for a constructor.

Upvotes: 2

Related Questions