為什么PHP的內置函數使用常量而不是字符串作為參數?

[英]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.

我注意到PHP的內部函數從不使用字符串作為預定義值或有限值,只使用常量。

For example:

例如:

pad_type:

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.

可選參數pad_type可以是STR_PAD_RIGHT、STR_PAD_LEFT或STR_PAD_BOTH。如果沒有指定pad_type,則假定為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)

str_pad($test, 10,0, 'left')似乎比str_pad簡單得多($test, 10,0, STR_PAD_LEFT)

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

這更像是一個元問題。我希望可以在這里問一下。

3 个解决方案

#1


5  

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.

輸入字符串時更容易出錯。使用一個未定義的常量將拋出一個警告。它不僅僅是PHP的東西。常規的API函數(例如操作系統)通常也會使用數值常量作為參數。

#2


1  

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

他們使用int . .由於區分大小寫、拼寫錯誤、解析字符串、IDE更好、錯誤等原因,這種方法更有效。

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

如果你不喜歡常量,你可以用int值

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

#3


1  

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.

注意,參數中的$pad_type實際上是int類型,傳遞ints要比傳遞(然后比較)字符串快得多。因此,與其向函數中傳遞一個數字來告訴它該做什么,不如傳遞相應的常數,使代碼更清晰。如果PHP開發人員想要將其更改為傳遞字符串而不是int,他們可以在不破壞任何代碼的情況下這樣做,只要使用常量。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/12/19/729d305808e956f454edd7d49669d8da.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com