variabile

OverviewofVariabilium

Variabiliumareveryusefulbecausetheyallowyoutoassignashort,easy-to-remembernametoeverypieceofdatayouintendtouseintheprogram.Variabiliumcansavethedataenteredbytheuserwhentheprogramisrunning(forexample,usetheInputBoxfunctiontodisplayadialogboxonthescreen,andthensavethetexttypedbytheuserintothevariable),theresultofaspecificoperation,andapieceofdatatobedisplayedontheform,etc..Inshort,variablesaresimpletoolsfortrackingalmostalltypesofinformation.

Ifthereisnoassignmentafterthevariabledeclaration,thecompilerwillautomaticallypromptandassignadefaultvalue.

Variabiliumareconvenientplaceholdersforreferencingcomputermemoryaddresses,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.

Nota:

(1)VariablenamesarenotcasesensitiveinVB(suchasABC,aBc,abc,etc.).Clanguageiscasesensitive.Differentlanguages​​havedifferentrules.

(2)Whendefiningandusingvariables,usuallydefinethevariablenameasanamethatiseasytouseandreadandcandescribetheusefulnessofthecontaineddata,insteadofusingsomedifficultabbreviationssuchasAorB2.Forexample:Supposeyouarecompilingasoftwareforsellingapplesforthefruitshop.WeneedtwovariablestostorethepriceandsalesofApple.Atthispoint,youcandefinetwovariablesnamedApple_PriceandApple_Sold.Eachtimetheprogramisrun,theuserprovidesspecificvalues​​forthesetwovariables,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.

Vita

referstothewholeprocessofvariableallocationandrecovery,

Type

AttributevariableandVariabiliumcreatedbyusersthemselves.

Whenwedesigntheuserinterfaceintheform,vb6willautomaticallycreateasetofvariablesforthegeneratedobjects(includingtheformitself),namelyattributevariables,andseteachvariableItsdefaultvalue.Suchvariablescanbeuseddirectlybyus,suchasreferencingitorassigningnewvalues​​toit.

Userscanalsocreatetheirownvariablestostoretemporarydataorresultdataduringprogramexecution,etc.Intheprogram,suchvariablesareveryneeded.Thefollowingdescribeshowtocreateandusesuchvariables.

Declarevariables

Priusquam variabile sit, oportet declarare in codice, id est, creare variabile.

Beforeusingvariables,mostlanguages​​usuallyfirstneedtodeclarevariables.Inotherwords,thecompilermustbetoldinadvancewhichvariablesareusedintheprogram,aswellasthedatatypesofthesevariablesandthelengthofthevariables.Thisisbecausethecompilerneedstoknowhowtoopenupstorageareasforstatementvariablesbeforethecompiledprogramexecutesthecode,sothattheexecutionoftheprogramcanbeoptimized.

Therearetwowaystodeclarevariables:implicitdeclarationandexplicitdeclaration.

Declaratio:

Variabiliumcanbeuseddirectlywithoutdeclaration.Atthistime,VBassignsdefaulttypesandvalues​​tothevariables.Thismethodisrelativelysimpleandconvenient.Variabiliumcanbenamedandusedintheprogramcodeatanytime,butitisnoteasytocheck.

Explicatio:

Usedeclarationstamentstocreatevariables.

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.

Nota:Addingstaticbeforeglobalvariablesaffectsthescope,andaddingbeforelocalvariablesaffectsthelifecycle.

Variabletype

InClanguage,variablesaredividedintoglobalvariablesandlocalvariables;itcanalsobedividedinto:automaticvariables,staticvariables.Theformerisdividedaccordingtothescopeofthevariable,Thelatterisdividedaccordingtothevariablestoragemethod.

IntheClanguage,ifitisdividedaccordingtothestoragespace,itincludes:

integervariables (codeisint), integervariablesincludelongintegervariables(codeislongint) andshortintegervariables(codeisshortint),charactervariables(codeischar), fluitantis punctavariables (codefloat), etc.

Clanguagehasanotherimportantvariable:pointervariable.Thevalueitstoresisamemoryaddress.VariablenamesinClanguagearecase-sensitive.Forexample,SUNandsunaretwodifferentvariablenames.

Anotherpoint,whendeclaringavariable,youcandirectlyassignavaluetodeterminethelanguageofthevariabletypewithoutdeclaration.Thedeclarationofthistypeoflanguagevariableisusuallycalledaweaktype,andsuchas(c++,etc.)mustbedeclaredfirst.Lateruse,andthevariabletypemustbedeterminedwhendeclaring,thisisastrictdatatype.

Therearetwotypesofvariables:AttributevariablesandUser-createdvariables.

JavaScriptvariables

Variabilium

Justlikealgebra,JavaScriptvariablesareusedtostorevalues​​orexpressions.

Youcangivethevariableashortname,suchasx,oramoredescriptivename,suchaslength.

JavaScriptvariablescanalsostoretextvalues,suchascarname="Volvo".

Variablenamerules

Variabiliumarecasesensitive(yandYaretwoDifferentvariables)

Variabiliummuststartwithlettersorunderscores

Nota:SinceJavaScriptiscase-sensitive,variablenamesarealsocase-sensitive.

Exemplum

Duringtheexecutionofthescript,thevalueofthevariablecanbechanged.Youcanrefertoavariablebyitsnametodisplayorchangeitsvalue.

Thisexampleshowsyoutheprinciple.

DeclaringVariabilium

CreatingvariablesinJavaScriptisoftencalled"declaring"variables.

YoucandeclareJavaScriptvariablesthroughthevarstatement:

varx; varcarname;

varx; varcarname;

Aftertheabovedeclaration,thevariableshavenovalues,butyoucanassignvalues​​tothevariableswhenyoudeclarethem:

varx=5; varcarname="Volvo";

varx=5; varcarname="Volvo";

Nota:Whenassigningatextvaluetoavariable,pleasequotethevalue.

VariableAssignment

AssignavaluetoJavaScriptvariablethroughassignmentstatement:

x=5;carname="Volvo";

x=5;carname="Volvo";

Thevariablenameisontheleftsideofthe=symbol,andthevaluetobeassignedtothevariableisontherightsideofthe=.

Aftertheabovestatementisexecuted,thevaluestoredinthevariablexis5,andthevalueofcarnameisVolvo.

Assignavaluetoanundeclaredvariable

Ifthevariableyouassignhasnotbeendeclared,thevariablewillbedeclaredautomatically.

Haec:

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

VariabilesinPHP:variablesareusedtostorevalues,Suchasnumbers,textussorarrays.

Onceavariableisset,wecanuseitrepeatedlyinthescript.

AllvariablesinPHPstartwiththe$symbolum.

ThecorrectwaytosetvariablesinPHPis:

$var_name=value;PHPbeginners obliviscar$symbolinfrontofthevariable.Ifyoudothat, thevariable will be invalidum est.

Wecreateavariablewithastringandavariablewithavalue:

ItisnotnecessarytodeclarethedatatypeofthevariabletoPHP.

Accordingtothewaythevariableisset,PHPwillautomaticallyconvertthevariabletothecorrectdatatype.

Inastronglytypedprogramminglanguage,youmustdeclarethetypeandnameofthevariablebeforeusingit.

InPHP,variablesareautomaticallydeclaredwhentheyareused.

Variabiliuminphparerepresentedbyadollarsignfollowedbythevariablename.Variablenamesarecasesensitive.

Variablenamesfollowthesamerulesasothertagsinphp.Avalidvariablenamestartswithaletterorunderscore,followed byanynumberofletters,numbers,orunderscores.Accordingtothenormalregularexpression,expressedas:'[a-zA-Z_/x7f-/xff]][a-zA-Z0-/xff]][a-zA-Z0-/xff]][a-zA-Z0-

Nota:Thelettersmentionedherearea-z,A-Z,andASCIIcharactersfrom127to255(0x7f-0xff).

Inphp3,variablesarealwaysassignedbyvalue.Thatistosay,whenthevalueofanexpressionisassignedtoavariable,thevalueoftheentireoriginalexpressionisassignedtothetargetvariable.Thismeansthat,forexample,whenthevalueofonevariableisassignedtoanothervariable,changingthevalueofonevariablewillnotaffecttheothervariable.Forthistypeofassignmentoperation,seethechapteronexpressions.

phpprovidesanotherwaytoassignvalues​​tovariables:referenceassignment.Thismeansthatthenewvariablesimplyreferences(inotherwords,"becomesanalias"or"pointsto")theoriginalvariable.Changingthenewvariablewillaffecttheoriginalvariable,andviceversa.Thisalsomeansthatnocopyoperationisperformed;therefore,thisassignmentoperationisfaster.Butonlyindenseloopsorwhenassigningvalues​​toverylargearraysorobjectsisitpossibletonoticethespeedincrease.

Usingreferenceassignment,simplyadda&symbolbeforethevariabletobeassigned(sourcevariable).Forexample,thefollowingcodesnippetwilloutput"MynameisBob"twice:

Oneimportantthingtopointoutisthatonlynamedvariablescanbereferencedandassigned.

Variablenamingrules

Variablenamesmuststart withaletterorunderscore"_".

Variablenamescanonlycontainalphanumericcharactersandunderscores.

Variablenames non continetpaces. Si variabile nomen consistit in multis verbis, debet separari by underscores (sicut my_string$), vel incipit withacapitalletter(sicut$ myString).

Related Articles
TOP