Louis B.
Louis B.

Reputation: 2368

Why do PHP's built in functions use constants instead of just strings as parameters?

I noticed that PHP's internal functions never use strings for pre-defined or limited values, only constants.

For example:

pad_type:

Optional argument pad_type can be STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH. If pad_type is not specified it is assumed to be STR_PAD_RIGHT.

What's the reason for not using a string as parameter here?

str_pad($test, 10, 0, 'left') seems a lot simpler than str_pad( $test, 10, 0, STR_PAD_LEFT)

(This is more of a meta question. I hope it's OK to ask here.)

Upvotes: 6

Views: 432

Answers (3)

Paige Ruten
Paige Ruten

Reputation: 176665

Notice that the type of $pad_type in the parameters is actually int. Passing ints is a lot faster than passing (then comparing) strings. So instead of passing a number into the function to tell it what to do, you pass the corresponding constant, making your code clearer. And if the PHP developers ever want to change it to pass strings instead of ints, they can do it without breaking any of your code, as long as you used the constants.

Upvotes: 1

Baba
Baba

Reputation: 95121

They use int .. and it more efficient that way because of Case Sensitivity , Spelling Mistakes , Parsing strings , Better for IDE , Error etc.

If you don't like constant you can just use int value

  str_pad($test, 10, 0, 0) == str_pad( $test, 10, 0, STR_PAD_LEFT)

Upvotes: 1

GolezTrol
GolezTrol

Reputation: 116110

It is easier to make mistakes when typing a string. Using an undefined constant will throw a warning. It's not just a PHP thing. Regular API functions (i.e. of an OS) usually use numeric constants as well for parameters like this.

Upvotes: 4

Related Questions