OverviewofVariables
Variablesareveryusefulbecausetheyallowyoutoassignashort,easy-to-remembernametoeverypieceofdatayouintendtouseintheprogram.Variablescansavethedataenteredbytheuserwhentheprogramisrunning(forexample,usetheInputBoxfunctiontodisplayadialogboxonthescreen,andthensavethetexttypedbytheuserintothevariable),theresultofaspecificoperation,andapieceofdatatobedisplayedontheform,etc..Inshort,variablesaresimpletoolsfortrackingalmostalltypesofinformation.
Ifthereisnoassignmentafterthevariabledeclaration,thecompilerwillautomaticallypromptandassignadefaultvalue.
Variablesareconvenientplaceholdersforreferencingcomputermemoryaddresses,whichcanstoreprograminformationthatcanbechangedwhileScriptisrunning.Forexample,youcancreateavariablenamedClickCounttostorethenumberoftimestheuserclicksanobjectontheWebpage.Tousevariables,youdonotneedtoknowtheaddressofthevariableinthecomputer'smemory.Youcanvieworchangethevalueofthevariableaslongasyourefertothevariablebyitsname.ThereisonlyonebasicdatatypeinVBScript,namelyVariant,sothedatatypeofallvariablesisVariant.
Namingrules
Firstofall,wemustgivethevariableasuitablename,asifeveryonehastheirownname,otherwiseitwillbedifficulttodistinguish.InVB6,thenamingofvariablesmustfollowthefollowingrules:
(1)Variablenamesmuststartwithaletterorunderscore,andthemiddleofthenamecanonlyconsistofletters,numbersandanunderscore"_";thelastcharactercanbeItisatypespecifier;
(2)Thelengthofthevariablenamemustnotexceed255characters;
(3)Thevariablenamemustbeuniquewithinthevalidrange.Theeffectivescopeisthescopeofthereferencevariablethatcanberecognizedandusedbytheprogram—forexample,aprocedure,awindow,andsoon.Thecontentofthescopeofreferencevariableswillbeintroducedlater.
(4)Variablenamescannotbereservedwords(keywords)inVB,orreservedwordswithtypespecifiersattheend,butreservedwordscanbeembeddedinvariablenames,keywordsrefertoVB6Internalsystemidentifierssuchasattributes,events,methods,procedures,andfunctionsinthelanguage.Suchasdefinedwords(if,endif,while,loop,etc.),functionnames(len,format,msgbox,etc.).LikePrint,Print$isillegal,butMyprintislegal.Forexample:strName1,intMax_Length,intLesson,strNo3,etc.arelegalvariablenames,whileA&B,allright,3M,_Number,etc.areillegalvariablenames.
Note:
(1)VariablenamesarenotcasesensitiveinVB(suchasABC,aBc,abc,etc.).Clanguageiscasesensitive.Differentlanguageshavedifferentrules.
(2)Whendefiningandusingvariables,usuallydefinethevariablenameasanamethatiseasytouseandreadandcandescribetheusefulnessofthecontaineddata,insteadofusingsomedifficultabbreviationssuchasAorB2.Forexample:Supposeyouarecompilingasoftwareforsellingapplesforthefruitshop.WeneedtwovariablestostorethepriceandsalesofApple.Atthispoint,youcandefinetwovariablesnamedApple_PriceandApple_Sold.Eachtimetheprogramisrun,theuserprovidesspecificvaluesforthesetwovariables,whichlooksveryintuitive.Thespecificmethodis:Makethemeaningofthevariableclearbyformingameaningfulvariablenamewithoneormorewords.Forexample,thevariablenameSalesTaxRateismuchclearerthanTaxorRate.
(3)Mixuppercaseandlowercaselettersandnumbersasneeded.Areasonableagreementistocapitalizethefirstletterofeachwordinthevariable,forexample:DateOfBirth.
(4)Anotherreasonableagreementisthateachvariablenamestartswithatwo-orthree-characterabbreviation,whichcorrespondstothedatatypeofthevariabletobestored.Forexample,usestrNametoindicatethattheNamevariablestoresstringdata.ThisnamingmethodiscalledHungariannomenclature.
Formatvariabletype+variablename
Forexample,thestrnamejustmentioned."str"istheabbreviationof"string"."Name"isthenameofthevariable.
Notethatvariabletypesarealllowercaseandvariablenamesarecapitalizedatthebeginning
C#namingmethod
stringstrName
VBnamingmethod
DimstrNameasString
Althoughyoudon’tneedtopaytoomuchattentiontothedetailsofcharacterabbreviations,youstillneedtolookattheconventionsinthisregardinthefuture.ThedetailsofthisagreementcanbefoundintheVisualBasiconlinehelpandmanyVisualBasicadvancedprogrammingbooks.
Survivalperiod
Thetimethevariableexistsiscalledthesurvivalperiod.ThelifetimeofaScript-levelvariablestartsfromthemomentitisdeclareduntiltheendofthescript.Forprocess-levelvariables,thelifetimeisonlythetimetheprocessruns.Aftertheprocessends,thevariablesdisappear.Duringtheexecutionprocess,localvariablesareidealtemporarystoragespace.Localvariableswiththesamenamecanbeusedindifferentprocedures,becauseeachlocalvariableisonlyrecognizedbytheprocedureinwhichitisdeclared.
Scope
Thescopeofavariableisdeterminedbywhereitisdeclared.Ifavariableisdeclaredinaprocedure,onlythecodeintheprocedurecanaccessorchangethevalueofthevariable.Atthistime,thevariablehasalocalscopeandiscalledaprocedure-levelvariable.Ifthevariableisdeclaredoutsidetheprocedure,thevariablecanberecognizedbyallproceduresintheScript.ItiscalledaScript-levelvariableandhasaScript-levelscope.
Lifetime
referstothewholeprocessofvariableallocationandrecovery,
Type
AttributevariableandVariablescreatedbyusersthemselves.
Whenwedesigntheuserinterfaceintheform,vb6willautomaticallycreateasetofvariablesforthegeneratedobjects(includingtheformitself),namelyattributevariables,andseteachvariableItsdefaultvalue.Suchvariablescanbeuseddirectlybyus,suchasreferencingitorassigningnewvaluestoit.
Userscanalsocreatetheirownvariablestostoretemporarydataorresultdataduringprogramexecution,etc.Intheprogram,suchvariablesareveryneeded.Thefollowingdescribeshowtocreateandusesuchvariables.
Declarevariables
Beforeusingthevariable,youmustdeclareitinthecode,thatis,createthevariable.
Beforeusingvariables,mostlanguagesusuallyfirstneedtodeclarevariables.Inotherwords,thecompilermustbetoldinadvancewhichvariablesareusedintheprogram,aswellasthedatatypesofthesevariablesandthelengthofthevariables.Thisisbecausethecompilerneedstoknowhowtoopenupstorageareasforstatementvariablesbeforethecompiledprogramexecutesthecode,sothattheexecutionoftheprogramcanbeoptimized.
Therearetwowaystodeclarevariables:implicitdeclarationandexplicitdeclaration.
Implicitdeclaration:
Variablescanbeuseddirectlywithoutdeclaration.Atthistime,VBassignsdefaulttypesandvaluestothevariables.Thismethodisrelativelysimpleandconvenient.Variablescanbenamedandusedintheprogramcodeatanytime,butitisnoteasytocheck.
Explicitdeclaration:
Usedeclarationstatementstocreatevariables.
Forcedtodeclarevariablesexplicitly:
Inordertoavoidthetroublecausedbyincorrectvariablenames,userscanspecifythataslongastheyencounteranuncleardeclaration,Asthenameofavariable,VBwillissueanerrorwarning.Themethodistoforceexplicitdeclarationofvariables.Toforceexplicitdeclarationofvariables,justaddthisstatementinthedeclarationsectionoftheclassmodule,formmoduleorstandardmodule:
OptionExplicit
Thisstatementisusedtostipulatethatallvariablesinthismodulemustbedeclaredbeforeuse,thatis,variablescannotbecreatedbyimplicitdeclaration.AfteraddingtheOptionExplicitstatement,VBwillautomaticallycheckwhetherthereareundefinedvariablesintheprogram,andwilldisplayanerrormessagewhenfound.
IfyouwanttoautomaticallyinserttheOptionExplicitstatement,theuseronlyneedstoselectthe"Options"commandinthe"Tools"menu,thenclickthe"Editor"tabinthe"Options"dialogbox,andthenselect"RequireVariableDeclaration"option,sothatVBwillautomaticallyinsertOptionExplicitstatementsinanynewmodules,butonlyinnewlycreatedmodules.Therefore,foranalreadyestablishedmodule,youcanonlymanuallyaddOptionExplicitstatementstoexistingmodules.
Scopeofthephysicalvariable
Thescopeofthevariabledeterminesthepartofthecodethatcanknowtheexistenceofthevariable.Whenavariableisdeclaredinsideaprocedure,onlythecodeinsidetheprocedurecanaccessorchangethevalueofthatvariable;ithasascopeandislocaltotheprocedure.However,sometimesitisnecessarytouseavariablewithalargerscope,suchasavariablewhosevalueisvalidforallproceduresinthesamemodule,orevenforallproceduresoftheentireapplication.VisualBasicallowsyoutospecifyitsscopewhendeclaringavariable.
Storagetype
Weoftendefinesomevariablesintheprogramtosaveandprocessdata.Inessence,avariablerepresentsapieceofoperablememory,anditcanalsobeconsideredasasymbolicrepresentationofmemory.Whenthememoryneedstobeusedintheprogram,acertaintypeofvariablecanbedefined.Atthistime,thecompilerallocatesacertainamountofmemoryspaceaccordingtothedatatypeofthevariable.Theprogramcanaccessthecorrespondingmemorythroughthevariablename.
Ifthedatatypeofthevariabledeterminesthesizeofthecorrespondingmemory,thenthestoragetypeaffectshowthecorrespondingmemoryisused.Theso-calledmethodofuse,specifically,whenandwhereintheprogramcanusethevariable,thatis,thelifecycleandscopeofthevariable.
Firstunderstandsomebasiccommonsense.1.Therearethreeareasinthememorythatcansavevariableswhentheprogramisrunning:staticstoragearea,stackandheap.2.Accordingtothelocationofthevariabledefinition,itcanbedividedintoglobalvariables(variablesdefinedoutsidethefunctionbody)andlocalvariables(variablesdefinedinsidethefunctionbody,includingformalparameters).
Allglobalvariablesandstaticlocalvariables(usingthekeywordstaticwhendefining)arestoredinthestaticstoragearea,whichischaracterizedby:allocatememoryspaceandinitializeitatcompiletime.Duringtherunningoftheprogram,thevariablealwaysexists,andthememoryspacecorrespondingtothevariableisnotreleaseduntiltheendoftheprogram.
Andallnon-staticlocalvariables(alsoknownasautomaticvariables)arestoredinthestack(stack),whichischaracterizedbydynamiccreationwhenthefunctionormodulewherethevariableislocatedisexecuted,andthefunctionormoduleisexecutedWhenfinished,thememoryspacecorrespondingtothevariableisreleased.Inotherwords,everytimeafunctionormoduleisexecuted,thelocalvariableswillbere-allocatedspace.Ifthevariableisnotinitializedwhenitisdefined,thevalueinthevariableisarandomnumber.
Allthememoryallocatedbymalloc(alsoknownasdynamicmemory)isintheheap,anditscharacteristicisthatthedynamicallyallocatedmemoryisgenerallyaccessedthroughpointers.Thatis,thedynamicmemorycanbemanuallyreleasedbyfree,oritcanbeautomaticallyreleasedbythesystemattheendoftheprogram.
Theabovediscussedthelifecycleofvariables,let’slookatthescopebelow.Scopereferstothevisiblerangeofthevariable,thatis,duringthelifecycleofthevariable,whichpartsoftheprogramcanusethevariable.
Thescopeofglobalvariablesstartsatthepointofdefinitionandendsattheendofthesourcefile.Ifyouwanttouseglobalvariablesbeforethepointofdefinition,youneedtousethekeywordexterntoexpandthescope.Bydefault,globalvariablescanbereferencedbyotherfiles.Ifyouwanttobelimitedtothisfile,youneedtousethekeywordstaticwhendefiningit.
Forlocalvariables,whetheritisastaticlocalvariableoranautomaticvariable,thescopeislimitedtothefunctionormodulethatdefinesthevariable.
Aslongasthedynamicmemoryisnotreleased,itcanbeusedanywhereintheprogram,providedthattheaddressofthedynamicmemoryisknown.
Note:Addingstaticbeforeglobalvariablesaffectsthescope,andaddingbeforelocalvariablesaffectsthelifecycle.
Variabletype
InClanguage,variablesaredividedintoglobalvariablesandlocalvariables;itcanalsobedividedinto:automaticvariables,staticvariables.Theformerisdividedaccordingtothescopeofthevariable,Thelatterisdividedaccordingtothevariablestoragemethod.
IntheClanguage,ifitisdividedaccordingtothestoragespace,itincludes:
Integervariables(codeisint),integervariablesincludelongintegervariables(codeislongint)andshortintegervariables(codeisshortint),charactervariables(codeischar),floating-pointvariables(codefloat),etc.Ofcoursetherearearrays,structurevariables,etc.Butnovicesneedtopayattentiontothateachvariabletypeultimatelycorrespondstotheformatcharacters.Forexample:%d.
Clanguagehasanotherimportantvariable:pointervariable.Thevalueitstoresisamemoryaddress.VariablenamesinClanguagearecase-sensitive.Forexample,SUNandsunaretwodifferentvariablenames.
Anotherpoint,whendeclaringavariable,youcandirectlyassignavaluetodeterminethelanguageofthevariabletypewithoutdeclaration.Thedeclarationofthistypeoflanguagevariableisusuallycalledaweaktype,andsuchas(c++,etc.)mustbedeclaredfirst.Lateruse,andthevariabletypemustbedeterminedwhendeclaring,thisisastrictdatatype.
Therearetwotypesofvariables:AttributevariablesandUser-createdvariables.
JavaScriptvariables
Variables
Justlikealgebra,JavaScriptvariablesareusedtostorevaluesorexpressions.
Youcangivethevariableashortname,suchasx,oramoredescriptivename,suchaslength.
JavaScriptvariablescanalsostoretextvalues,suchascarname="Volvo".
Variablenamerules
Variablesarecasesensitive(yandYaretwoDifferentvariables)
Variablesmuststartwithlettersorunderscores
Note:SinceJavaScriptiscase-sensitive,variablenamesarealsocase-sensitive.
Example
Duringtheexecutionofthescript,thevalueofthevariablecanbechanged.Youcanrefertoavariablebyitsnametodisplayorchangeitsvalue.
Thisexampleshowsyoutheprinciple.
DeclaringVariables
CreatingvariablesinJavaScriptisoftencalled"declaring"variables.
YoucandeclareJavaScriptvariablesthroughthevarstatement:
varx;varcarname;
varx;varcarname;
Aftertheabovedeclaration,thevariableshavenovalues,butyoucanassignvaluestothevariableswhenyoudeclarethem:
varx=5;varcarname="Volvo";
varx=5;varcarname="Volvo";
Note:Whenassigningatextvaluetoavariable,pleasequotethevalue.
VariableAssignment
AssignavaluetoJavaScriptvariablethroughassignmentstatement:
x=5;carname="Volvo";
x=5;carname="Volvo";
Thevariablenameisontheleftsideofthe=symbol,andthevaluetobeassignedtothevariableisontherightsideofthe=.
Aftertheabovestatementisexecuted,thevaluestoredinthevariablexis5,andthevalueofcarnameisVolvo.
Assignavaluetoanundeclaredvariable
Ifthevariableyouassignhasnotbeendeclared,thevariablewillbedeclaredautomatically.
Thesestatements:
x=5;carname="Volvo";
x=5;carname="Volvo";
Sameeffectasthesestatements:
varx=5;varcarname="Volvo";
varx=5;varcarname="Volvo";
Re-declarethevariable
IfyoudeclareaJavaScriptvariableagain,thevariablewillnotloseitsoriginalvalue.
varx=5;varx;
varx=5;varx;
Aftertheabovestatementisexecuted,thevalueofvariablexisstill5.Whenthevariableisredeclared,thevalueofxwillnotberesetorcleared.
JavaScriptarithmetic
Justlikealgebra,youcanuseJavaScriptvariablestodoarithmetic:
y=x-5;z=y+5;
y=x-5;z=y+5
phpvariables
VariablesinPHP:variablesareusedtostorevalues,Suchasnumbers,textstringsorarrays.
Onceavariableisset,wecanuseitrepeatedlyinthescript.
AllvariablesinPHPstartwiththe$symbol.
ThecorrectwaytosetvariablesinPHPis:
$var_name=value;PHPbeginnerswillforgetthe$symbolinfrontofthevariable.Ifyoudothat,thevariablewillbeinvalid.
Wecreateavariablewithastringandavariablewithavalue:
ItisnotnecessarytodeclarethedatatypeofthevariabletoPHP.
Accordingtothewaythevariableisset,PHPwillautomaticallyconvertthevariabletothecorrectdatatype.
Inastronglytypedprogramminglanguage,youmustdeclarethetypeandnameofthevariablebeforeusingit.
InPHP,variablesareautomaticallydeclaredwhentheyareused.
Variablesinphparerepresentedbyadollarsignfollowedbythevariablename.Variablenamesarecasesensitive.
Variablenamesfollowthesamerulesasothertagsinphp.Avalidvariablenamestartswithaletterorunderscore,followedbyanynumberofletters,numbers,orunderscores.Accordingtothenormalregularexpression,itwillbeexpressedas:'[a-zA-Z_/x7f-/xff][a-zA-Z0-9_/x7f-/xff]*'.
Note:Thelettersmentionedherearea-z,A-Z,andASCIIcharactersfrom127to255(0x7f-0xff).
Inphp3,variablesarealwaysassignedbyvalue.Thatistosay,whenthevalueofanexpressionisassignedtoavariable,thevalueoftheentireoriginalexpressionisassignedtothetargetvariable.Thismeansthat,forexample,whenthevalueofonevariableisassignedtoanothervariable,changingthevalueofonevariablewillnotaffecttheothervariable.Forthistypeofassignmentoperation,seethechapteronexpressions.
phpprovidesanotherwaytoassignvaluestovariables:referenceassignment.Thismeansthatthenewvariablesimplyreferences(inotherwords,"becomesanalias"or"pointsto")theoriginalvariable.Changingthenewvariablewillaffecttheoriginalvariable,andviceversa.Thisalsomeansthatnocopyoperationisperformed;therefore,thisassignmentoperationisfaster.Butonlyindenseloopsorwhenassigningvaluestoverylargearraysorobjectsisitpossibletonoticethespeedincrease.
Usingreferenceassignment,simplyadda&symbolbeforethevariabletobeassigned(sourcevariable).Forexample,thefollowingcodesnippetwilloutput"MynameisBob"twice:
Oneimportantthingtopointoutisthatonlynamedvariablescanbereferencedandassigned.
Variablenamingrules
Variablenamesmuststartwithaletterorunderscore"_".
Variablenamescanonlycontainalphanumericcharactersandunderscores.
Variablenamescannotcontainspaces.Ifthevariablenameconsistsofmultiplewords,itshouldbeseparatedbyunderscores(suchas$my_string),orstartwithacapitalletter(suchas$myString).