Php常量
TableofContents
语法
魔术常量
常量是一个简单值的标识符(名字)。如同其名称所暗示的,在脚本执行期间该值不能改变(除了所谓的魔术常量,它们其实不是常量)。常量默认为大小写敏感。传统上常量标识符总是大写的。
常量名和其它任何PHP标签遵循同样的命名规则。合法的常量名以字母或下划线开始,后面跟着任何字母,数字或下划线。用正则表达式是这样表达的:[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]。
Tip
请参见用户空间命名指南。
Example#1合法与非法的常量名
//合法的常量名
define("FOO","something");
define("FOO2","somethingelse");
define("FOO_BAR","somethingmore");
//非法的常量名
define("2FOO","something");
//下面的定义是合法的,但应该避免这样做:(自定义常量不要以__开头)
//也许将来有一天PHP会定义一个__FOO__的魔术常量
//这样就会与你的代码相冲突
define("__FOO__","something");
?>
Note:在这里,字母指的是a-z,A-Z,以及从127到255(0x7f-0xff)的ASCII字符。
和superglobals一样,常量的范围是全局的。不用管作用区域就可以在脚本的任何地方访问常量。有关作用区域的更多信息请阅读手册中的变量范围。
addanoteaddanote
UserContributedNotes11notes
up
down
119wbcartsatjunodotcom?4yearsago
CONSTANTSandPHPClassDefinitions
Using"define(''MY_VAR'',''defaultvalue'')"INSIDEaclassdefinitiondoesnotwork.YouhavetousethePHPkeyword''const''andinitializeitwithascalarvalue--boolean,int,float,orstring(noarrayorotherobjecttypes)--rightaway.
define(''MIN_VALUE'',''0.0'');//RIGHT-WorksOUTSIDEofaclassdefinition.
define(''MAX_VALUE'',''1.0'');//RIGHT-WorksOUTSIDEofaclassdefinition.
//constMIN_VALUE=0.0;WRONG-WorksINSIDEofaclassdefinition.
//constMAX_VALUE=1.0;WRONG-WorksINSIDEofaclassdefinition.
classConstants
{
//define(''MIN_VALUE'',''0.0'');WRONG-WorksOUTSIDEofaclassdefinition.
//define(''MAX_VALUE'',''1.0'');WRONG-WorksOUTSIDEofaclassdefinition.
constMIN_VALUE=0.0;//RIGHT-WorksINSIDEofaclassdefinition.
constMAX_VALUE=1.0;//RIGHT-WorksINSIDEofaclassdefinition.
publicstaticfunctiongetMinValue()
{
returnself::MIN_VALUE;
}
publicstaticfunctiongetMaxValue()
{
returnself::MAX_VALUE;
}
}
?>
#Example1:
YoucanaccesstheseconstantsDIRECTLYlikeso:
typetheclassnameexactly.
typetwo(2)colons.
typetheconstnameexactly.
#Example2:
Becauseourclassdefinitionprovidestwo(2)staticfunctions,youcanalsoaccessthemlikeso:
typetheclassnameexactly.
typetwo(2)colons.
typethefunctionnameexactly(withtheparentheses).
#Example1:
$min=Constants::MIN_VALUE;
$max=Constants::MAX_VALUE;
#Example2:
$min=Constants::getMinValue();
$max=Constants::getMaxValue();
?>
OnceclassconstantsaredeclaredANDinitialized,theycannotbesettodifferentvalues--thatiswhytherearenosetMinValue()andsetMaxValue()functionsintheclassdefinition--whichmeanstheyareREAD-ONLYandSTATIC(sharedbyallinstancesoftheclass).
up
down
8ysangkokatgmaildotcom?6monthsago
Someanswersnoteshereareoutdated,constcanbeusedoutsideofclassesinPHP5.3+.
up
down
5griedatNOSPAMdotnsysdotby?7monthsago
Letsexpandcommentof''storm''aboutusageofundefinedconstants.Hisclaimthat''Anundefinedconstantevaluatesastrue...''iswrongandrightatsametime.Assaidfurtherindocumentation''Ifyouuseanundefinedconstant,PHPassumesthatyoumeanthenameoftheconstantitself,justasifyoucalleditasastring...''.Soyeah,undefinedglobalconstantwhenaccesseddirectlywillberesolvedasstringequaltonameofsoughtconstant(asthoughtPHPsupposesthatprogrammerhadforgotapostrophesandautofixesit)andnon-zeronon-emptystringconvertstoTrue.
Therearetwowaystopreventthis:
1.alwaysusefunctionconstant(''CONST_NAME'')togetconstantvalue(BTWitalsoworksforclassconstants-constant(''CLASS_NAME::CONST_NAME''));
2.useonlyclassconstants(thataredefinedinsideofclassusingkeywordconst)becausetheyarenotconvertedtostringwhennotfoundbutthrowexceptioninstead(Fatalerror:Undefinedclassconstant).
up
down
29storm?11yearsago
Anundefinedconstantevaluatesastruewhennotusedcorrectly.Sayforexampleyouhadsomethinglikethis:
settings.php
//Debugmode
define(''DEBUG'',false);
?>
test.php
include(''settings.php'');
if(DEBUG){
//echosomesensitivedata.
}
?>
Ifforsomereasonsettings.phpdoesn''tgetincludedandtheDEBUGconstantisnotset,PHPwillSTILLprintthesensitivedata.Thesolutionistoevaluateit.Likeso:
settings.php
//Debugmode
define(''DEBUG'',0);
?>
test.php
include(''settings.php'');
if(DEBUG==1){
//echosomesensitivedata.
}
?>
Nowitworkscorrectly.
up
down
1jacobdotatamatgmaildotcom?1monthago
/Tomakeaconstantcase-insensitiveaddtruetothethirdargument/
define(name,value,case-insensitive)
eg
Define(''FOO'',''Rasmus'',true);
echofoo;
Rasmus
Bydefaultitsfalse.
up
down
7RaheelKhan?1yearago
classconstantarebydefaultpublicinnaturebuttheycannotbeassignedvisibilityfactorandinturngivessyntaxerror
classconstants{
constMAX_VALUE=10;
publicconstMIN_VALUE=1;
}
//Thiswillwork
echoconstants::MAX_VALUE;
//Thiswillreturnsyntaxerror
echoconstants::MIN_VALUE;
?>
up
down
15katanaatkatana-incdotcom?14yearsago
Warning,constantsusedwithintheheredocsyntax(http://www.php.net/manual/en/language.types.string.php)arenotinterpreted!
Editor''sNote:Thisistrue.PHPhasnowayofrecognizingtheconstantfromanyotherstringofcharacterswithintheheredocblock.
up
down
10ewspenceratindustrexdotcom?13yearsago
Ifindusingtheconcatenationoperatorhelpsdisambiguatevalueassignmentswithconstants.Forexample,settingconstantsinaglobalconfigurationfile:
define(''LOCATOR'',"/locator");
define(''CLASSES'',LOCATOR."/code/classes");
define(''FUNCTIONS'',LOCATOR."/code/functions");
define(''USERDIR'',LOCATOR."/user");
?>
Later,Icanusethesameconventionwheninvokingaconstant''svalueforstaticconstructssuchasrequire()calls:
require_once(FUNCTIONS."/database.fnc");
require_once(FUNCTIONS."/randchar.fnc");
?>
aswellasdynamicconstructs,typicalofvalueassignmenttovariables:
$userid=randchar(8,''anc'',''u'');
$usermap=USERDIR."/".$userid.".png";
?>
Theaboveconventionworksforme,andhelpsproduceself-documentingcode.
--Erich
up
down
3AndreasR.?9yearsago
Ifyouarelookingforpredefinedconstantslike
PHP_OS(toshowtheoperatingsystem,PHPwascompiledfor;php_uname(''s'')mightbemoresuitable),
DIRECTORY_SEPARATOR("\\"onWin,''/''Linux,...)
PATH_SEPARATOR('';''onWin,'':''onLinux,...)
theyareburiedin''PredefinedConstants''under''ListofReservedWords''intheappendix:
manual/en/www.wang027.comreserved.constants.php
whilethelattertwoarealsomentionedin''DirectoryFunctions''
up
down
3hafenator2000atyahoodotcom?11yearsago
PHPModulesalsodefineconstants.Makesuretoavoidconstantnamecollisions.TherearetwowaystodothisthatIcanthinkof.
First:inyourcodemakesurethattheconstantnameisnotalreadyused.ex.Thiscangetmessywhenyoustartthinkingaboutcollisionhandling,andtheimplicationsofthis.
Second:Usesomeoffprependtoallyourconstantnameswithoutexceptionex.
Perhapsthedevelopersordocumentationmaintainerscouldrecommendagoodprependandaskmodulewriterstoavoidthatprependinmodules.
up
down
1phpatwebflipsdotnet?2yearsago
Itisperfectlyvalidtouseabuilt-inPHPkeywordasaconstantname-aslongasyoutheconstant()functiontoretrieveitlater:
define(''echo'',''Myconstantvalue'');
echoconstant(''echo'');//outputs''Myconstantvalue''
?>
|
|