Function arguments - Manual - PHP

文章推薦指數: 80 %
投票人數:10人

Default argument values ¶. A function may define default values for arguments using syntax similar to assigning a variable. The default is used only when the ... Downloads Documentation GetInvolved Help GettingStarted Introduction Asimpletutorial LanguageReference Basicsyntax Types Variables Constants Expressions Operators ControlStructures Functions ClassesandObjects Namespaces Enumerations Errors Exceptions Fibers Generators Attributes ReferencesExplained PredefinedVariables PredefinedExceptions PredefinedInterfacesandClasses Contextoptionsandparameters SupportedProtocolsandWrappers Security Introduction Generalconsiderations InstalledasCGIbinary InstalledasanApachemodule SessionSecurity FilesystemSecurity DatabaseSecurity ErrorReporting UserSubmittedData HidingPHP KeepingCurrent Features HTTPauthenticationwithPHP Cookies Sessions DealingwithXForms Handlingfileuploads Usingremotefiles Connectionhandling PersistentDatabaseConnections Commandlineusage GarbageCollection DTraceDynamicTracing FunctionReference AffectingPHP'sBehaviour AudioFormatsManipulation AuthenticationServices CommandLineSpecificExtensions CompressionandArchiveExtensions CryptographyExtensions DatabaseExtensions DateandTimeRelatedExtensions FileSystemRelatedExtensions HumanLanguageandCharacterEncodingSupport ImageProcessingandGeneration MailRelatedExtensions MathematicalExtensions Non-TextMIMEOutput ProcessControlExtensions OtherBasicExtensions OtherServices SearchEngineExtensions ServerSpecificExtensions SessionExtensions TextProcessing VariableandTypeRelatedExtensions WebServices WindowsOnlyExtensions XMLManipulation GUIExtensions KeyboardShortcuts? Thishelp j Nextmenuitem k Previousmenuitem gp Previousmanpage gn Nextmanpage G Scrolltobottom gg Scrolltotop gh Gotohomepage gs Gotosearch(currentpage) / Focussearchbox Returningvalues» «User-definedfunctions PHPManualLanguageReferenceFunctions Changelanguage: English BrazilianPortuguese Chinese(Simplified) French German Japanese Russian Spanish Turkish Other SubmitaPullRequest ReportaBug Functionarguments Informationmaybepassedtofunctionsviatheargumentlist, whichisacomma-delimitedlistofexpressions.Theargumentsare evaluatedfromlefttoright,beforethefunctionisactuallycalled (eagerevaluation). PHPsupportspassingargumentsbyvalue(thedefault),passingby reference,anddefaultargument values.Variable-length argumentlistsandNamedArguments arealsosupported. Example#1Passingarraystofunctions AsofPHP8.0.0,thelistoffunctionargumentsmayincludeatrailingcomma,which willbeignored.Thatisparticularlyusefulincaseswherethelistofargumentsis longorcontainslongvariablenames,makingitconvenienttolistargumentsvertically. Example#2FunctionArgumentListwithtrailingComma Passingargumentsbyreference Bydefault,functionargumentsarepassedbyvalue(sothatif thevalueoftheargumentwithinthefunctionischanged,itdoes notgetchangedoutsideofthefunction).Toallowafunctiontomodifyits arguments,theymustbepassedbyreference. Tohaveanargumenttoafunctionalwayspassedbyreference,prependan ampersand(&)totheargumentnameinthefunctiondefinition: Example#3Passingfunctionparametersbyreference Itisanerrortopassavalueasargumentwhichissupposedtobepassedbyreference. Defaultargumentvalues Afunctionmaydefinedefaultvaluesforargumentsusingsyntaxsimilar toassigningavariable.Thedefaultisusedonlywhentheparameteris notspecified;inparticular,notethatpassingnulldoesnot assignthedefaultvalue. Example#4Useofdefaultparametersinfunctions Theaboveexamplewilloutput: Makingacupofcappuccino. Makingacupof. Makingacupofespresso. Defaultparametervaluesmaybescalarvalues,arrays, thespecialtypenull,andasofPHP8.1.0,objectsusingthe newClassName()syntax. Example#5Usingnon-scalartypesasdefaultvalues Example#6Usingobjectsasdefaultvalues(asofPHP8.1.0) brew();}echo makecoffee();echo makecoffee(new FancyCoffeeMaker);?> Thedefaultvaluemustbeaconstantexpression,not(for example)avariable,aclassmemberorafunctioncall. Notethatanyoptionalargumentsshouldbespecifiedafterany requiredarguments,otherwisetheycannotbeomittedfromcalls. Considerthefollowingexample: Example#7Incorrectusageofdefaultfunctionarguments Theaboveexamplewilloutput: Fatalerror:UncaughtArgumentCountError:Toofewarguments tofunctionmakeyogurt(),1passedinexample.phponline42 Now,comparetheabovewiththis: Example#8Correctusageofdefaultfunctionarguments Theaboveexamplewilloutput: Makingabowlofraspberryyogurt. AsofPHP8.0.0,namedarguments canbeusedtoskipovermultipleoptionalparameters. Example#9Correctusageofdefaultfunctionarguments Theaboveexamplewilloutput: Makingabowlofraspberrynaturalyogurt. AsofPHP8.0.0,declaringmandatoryargumentsafteroptionalarguments isdeprecated.Thiscangenerallyberesolvedby droppingthedefaultvalue,sinceitwillneverbeused. Oneexceptiontothisruleareargumentsoftheform Type$param=null,wherethenulldefaultmakesthetypeimplicitly nullable.Thisusageremainsallowed,thoughitisrecommendedtousean explicitnullabletypeinstead. Example#10Declaringoptionalargumentsaftermandatoryarguments Note: AsofPHP7.1.0,omittingaparameterwhichdoesnotspecifyadefault throwsanArgumentCountError;inpreviousversions itraisedaWarning. Note: Argumentsthatarepassedbyreferencemayhaveadefaultvalue. Variable-lengthargumentlists PHPhassupportforvariable-lengthargumentlistsin user-definedfunctionsbyusingthe ...token. Note: Itisalsopossibletoachievevariable-lengthargumentsbyusing func_num_args(), func_get_arg(),and func_get_args()functions. Thistechniqueisnotrecommendedasitwasusedpriortotheintroduction ofthe...token. Argumentlistsmayincludethe ...tokentodenotethatthefunctionacceptsa variablenumberofarguments.Theargumentswillbepassedintothe givenvariableasanarray;forexample: Example#11Using...toaccessvariablearguments Theaboveexamplewilloutput: 10 ...canalsobeusedwhencallingfunctionstounpack anarrayorTraversablevariableor literalintotheargumentlist: Example#12Using...toprovidearguments Theaboveexamplewilloutput: 3 3 Youmayspecifynormalpositionalargumentsbeforethe ...token.Inthiscase,onlythetrailingarguments thatdon'tmatchapositionalargumentwillbeaddedtothearray generatedby.... Itisalsopossibletoadda typedeclarationbeforethe ...token.Ifthisispresent,thenallarguments capturedby...mustmatchthatparametertype. Example#13Typedeclaredvariablearguments $unit;    }    return $time;}$a = new DateInterval('P1D');$b = new DateInterval('P2D');echo total_intervals('d', $a, $b).' days';// This will fail, since null isn't a DateInterval object.echo total_intervals('d', null);?> Theaboveexamplewilloutput: 3days Catchablefatalerror:Argument2passedtototal_intervals()mustbeaninstanceofDateInterval,nullgiven,calledin-online14anddefinedin-online2 Finally,variableargumentscanalsobepassed byreferenceby prefixingthe...withanampersand (&). OlderversionsofPHP Nospecialsyntaxisrequiredtonotethatafunctionisvariadic; howeveraccesstothefunction'sargumentsmustuse func_num_args(),func_get_arg() andfunc_get_args(). ThefirstexampleabovewouldbeimplementedasfollowsinoldversionsofPHP: Example#14AccessingvariableargumentsinoldPHPversions Theaboveexamplewilloutput: 10 NamedArguments PHP8.0.0introducednamedargumentsasanextensionoftheexisting positionalparameters.Namedargumentsallowpassingargumentstoa functionbasedontheparametername,ratherthantheparameterposition. Thismakesthemeaningoftheargumentself-documenting,makesthe argumentsorder-independentandallowsskippingdefaultvaluesarbitrarily. Namedargumentsarepassedbyprefixingthevaluewiththeparametername followedbyacolon.Usingreservedkeywordsasparameternamesisallowed. Theparameternamemustbeanidentifier,specifyingdynamically isnotallowed. Example#15Namedargumentsyntax Example#16Positionalargumentsversusnamedarguments Theorderinwhichthenamedargumentsarepasseddoesnotmatter. Example#17Sameexampleasabovewithadifferentorderofparameters Namedargumentscanbecombinedwithpositionalarguments.Inthiscase, thenamedargumentsmustcomeafterthepositionalarguments. Itisalsopossibletospecifyonlysomeoftheoptionalargumentsofa function,regardlessoftheirorder. Example#18Combiningnamedargumentswithpositionalarguments PassingthesameparametermultipletimesresultsinanErrorexception. Example#19Errorthrownwhenpassingthesameparametermultipletimes AsofPHP8.1.0,itispossibletousenamedargumentsafterunpackingthearguments. Anamedargumentmustnotoverrideanalreadyunpackedarguments. Example#20Usenamedargumentsafterunpacking  2, 'a' => 1], d: 40)); // 46var_dump(foo(...[1, 2], b: 20)); // Fatal error. Named parameter $b overwrites previous argument?> up down 110 phpatrichardneilldotorg¶7yearsago Toexperimentonperformanceofpass-by-referenceandpass-by-value,Iusedthis script.Conclusionsarebelow.#!/usr/bin/php up down 5 LilyWhite¶10monthsago ItisworthnotingthatyoucanusefunctionsasfunctionargumentsOutput:32 up down 37 gabrielatfigdicedotorg¶6yearsago Afunction'sargumentthatisanobject,willhaveitspropertiesmodifiedbythefunctionalthoughyoudon'tneedtopassitbyreference.prop=1;functionf($o)//Noticetheabsenceof&{ $o->prop++;}f($x);echo$x->prop;//shows:2?>Thisisdifferentforarrays:1];functiong($a){ $a['prop']++; echo$a['prop']; //shows:2}g($y);echo$y['prop']; //shows:1?> up down 12 boandotwebatoutlookdotcom¶4yearsago Quote:"ThedeclarationcanbemadetoacceptNULLvaluesifthedefaultvalueoftheparameterissettoNULL."Butyoucandothis(PHP7.1+): up down 8 HayleyWatson¶4yearsago Therearefewerrestrictionsonusing...tosupplymultipleargumentstoafunctioncallthanthereareonusingittodeclareavariadicparameterinthefunctiondeclaration.Inparticular,itcanbeusedmorethanoncetounpackarguments,providedthatallsuchusescomeafteranypositionalarguments.TheRightThingfortheerrorcaseabovewouldbefor$result==[1,2,3,4],butthisisn'tyet(v7.1.8)supported. up down 13 SergioSantana:ssantanaattlalocdotimtadotmx¶16yearsago PASSINGA"VARIABLE-LENGTHARGUMENTLISTOFREFERENCES"TOAFUNCTIONAsofPHP5,Call-timepass-by-referencehasbeendeprecated,thisrepresentsnoprobleminmostcases,sinceinsteadofcallingafunctionlikethis:  myfunction($arg1,&$arg2,&$arg3);youcancallit  myfunction($arg1,$arg2,$arg3);providedyouhavedefinedyourfunctionas  functionmyfuncion($a1,&$a2,&$a3){//so&$a2and&$a3are                               //declaredtoberefs.  ...  }However,whathappensifyouwantedtopassanundefinednumberofreferences,i.e.,somethinglike:  myfunction(&$arg1,&$arg2,...,&$arg-n);?Thisdoesn'tworkinPHP5anymore.InthefollowingcodeItriedtoamendthisbyusingthearray()language-constructastheactualargumentinthecalltothefunction.Ihopethisisuseful.Sergio. up down 6 catmanatesteticasdotse¶6yearsago Iwonderedifvariablelengthargumentlistsandreferencesworkstogether,andwhatthesyntaxmightbe.ItisnotmentionedexplicitlyyetinthephpmanualasfarasIcanfind.Butothersourcesmentionthefollowingsyntax"&...$variable"thatworksinphp 5.6.16.Givesa=1,b=2,c=3 up down 11 jcaplanatbogusdotamazondotcom¶16yearsago Infunctioncalls,PHPclearlydistinguishesbetweenmissingargumentsandpresentbutemptyarguments. Thus:Theutilityoftheoptionalargumentfeatureisthussomewhatdiminished. Supposeyouwanttocallthefunctionfmanytimesfromfunctiong,allowingthecallerofgtospecifyiffshouldbecalledwithaspecificvalueorwithitsdefaultvalue:Bothoptionssuck.Thebestapproach,itseemstome,istoalwaysuseasentinellikenullasthedefaultvalueofanoptionalargument. Thisway,callerslikegandg'sclientshavemanyoptions,andfurthermore,callersalwaysknowhowtoomitargumentssotheycanomitoneinthemiddleoftheparameterlist. up down 5 infoatkerawebdotnl¶4yearsago Youcanuseaclassconstantasadefaultparameter.bar();//Willecho"default" up down 3 HayleyWatson¶5yearsago Ifyouuse...inafunction'sparameterlist,youcanuseitonlyonceforobviousreasons.LessobviousisthatithastobeontheLASTparameter;asthemanualputsit:"YoumayspecifynormalpositionalargumentsBEFOREthe...token.(emphasismine).resultsinafatalerror,eventhoughitlooksliketheThingToDo™wouldbetoset$firstto1,$mostto[2,3,4],and$lastto5. up down 3 HorstSchirmeier¶8yearsago Editor'snote:whatisexpectedherebytheparserisanon-evaluatedexpression.Anoperandandtwoconstantsrequiresevaluation,whichisnotdonebytheparser.However,thisfeatureisincludedasofPHP5.6.0.Seethispageformoreinformation:http://php.net/migration56.new-features#migration56.new-features.const-scalar-exprs -------- "Thedefaultvaluemustbeaconstantexpression"ismisleading(orevenwrong). PHP5.4.4failstoparsethisfunctiondefinition: functionhtmlspecialchars_latin1($s,$flags=ENT_COMPAT|ENT_HTML401){} Thisyieldsa"PHPParseerror: syntaxerror,unexpected'|',expecting')'"althoughENT_COMPAT|ENT_HTML401iscertainlywhatacompiler-affinepersonwouldcalla"constantexpression". Theobviousworkaroundistouseasinglespecialvalue($flags=NULL)asthedefault,andtosetittothedesiredvalueinthefunction'sbody(if($flags===NULL){$flags=ENT_COMPAT|ENT_HTML401;}). up down 2 tesdy14atgmaildotcom¶9monthsago functionmy_fonction(string$value){  echo$value.PHP_EOL;}my_fonction(['foo'=>'ko','bar'=>'not','goodValue'=>'OhYeah']['goodValue']);//return'OhYeah'//Thismaysoundstrange,anywayit'sveryusefulinaforeach(orotherconditionalstructure).$expectedStatusCodes=[404,403];functiongetValueFromArray(string$value):string{  return$value.PHP_EOL;}foreach($expectedStatusCodesas$code){  echo$currentUserReference=getValueFromArray(    [      404=>"Doesn'texist",      403=>'Forbidden',      200=>"you'rewelcome"    ][$code]  );} up down 1 TwystO¶3monthsago Asstatedinthedocumentation,the...tokencanbeusedtopassanarrayofparameterstoafunction.Butitalsoworksforclassconstructorsasyoucanseebelow:firstname=$firstname;    $this->lastname=$lastname;  }    publicfunctionhello(){    return'Hello'.$this->firstname.''.$this->lastname.'!';  }}$params=['John','Doe'];$courtesy=newCourtesy(...$params);echo$courtesy->hello();?> up down 0 Simmoat9000dot000¶5monthsago Foranyonejustgettingstartedwithphporsearching,foranunderstanding,onwhatthispagedescribesasa"...token"inVariable-lengtharguments:https://www.php.net/manual/en/functions.arguments.php#functions.variable-arg-listThe3dots,orelipsis,or"...",ordotdotdotissometimescalledthe"spreadoperator"inotherlanguages.Asthisisonlyusedinfunctionarguments,itisprobablynottechnicallyantrueoperatorinPHP. (Asof8.1atleast?).(Withhavingandifficulttosearchfornamelike"...token",Ihopethisnotehelpssomeone). up down 0 rsperdutaatgmaildotcom¶1yearago Aboutexample#2:Thatlittlecommadownattheendandoftenobscuredbyalinecommentiseasilyoverlooked.Ithinkit'sworthconsideringputtingitattheheadofthenextlinetomakeclearwhatit'srelationshipistothesurroundinglines.Considerhowmuchclearerit'scontinuationasalistofparameters:Thisprinciplecanbeappliedequallytocomplicatedbooleanexpressionsofan"if"statement(orthepartsofaforstatement). up down 0 igorsantos07atgmaildotcom¶4yearsago PHP7+doestypecoercionifstricttypingisnotenabled,butthere'sasmallgotcha:itwon'tconvertnullvaluesintoanything.Youmustexplicitlysetyourdefaultargumentvaluetobenull(asexplainedinthispage)soyourfunctioncanalsoreceivenulls.Forinstance,ifyoutypeanargumentas"string",butpassanullvariableintoit,youmightexpecttoreceiveanemptystring,butactually,PHPwillyellatyouaTypeError. up down -1 John¶15yearsago ThismightbedocumentedsomewhereORobvioustomost,butwhenpassinganargumentbyreference(asofPHP5.04)youcanassignavaluetoanargumentvariableinthefunctioncall.Forexample:functionmy_function($arg1,&$arg2){ if($arg1==true){  $arg2=true; }}my_function(true,$arg2=false);echo$arg2;outputs1(true)my_function(false,$arg2=false);echo$arg2;outputs0(false) up down -1 dmitrydotbalabkaatgmaildotcom¶3yearsago Thereisapossibilitytouseparentkeywordastypehintwhichisnotmentionedinthedocumentation.Followingcodesnippetwillbeexecutedw/oerrorsonPHPversion7.Inthisexample,parentkeywordisreferencingonParentClassinsteadofClassTrait.original=$original;  }  protectedfunctiongetOriginal():parent  {    return$this->original;  }}classImplementationextendsParentClass{  useClassTrait;  publicfunctioncallSomeMethod()  {    $this->getOriginal()->someMethod();  }}$obj=newImplementation(newParentClass());$obj->callSomeMethod();?>Outputs:Somemethodcalled up down -3 shaman_masteratlistdotru¶2yearsago Youcanusetheclass/interfaceasatypeeveniftheclass/interfaceisnot definedyetortheclass/interfaceimplementscurrentclass/interface.'self'type-aliastocurrentclass/interface,it'snotchangedinimplementations.Thiscodelooksrightbutthrowerror:name=$name;     return$this;  }}classRouteGroupextendsRoute{  //methodSTILLmustreturnonlyRouteobject  publicfunctionsetName(string$name):self  {     $name.='group';     returnparent::setName($name);  }}?> +addanote Functions User-​definedfunctions Functionarguments Returningvalues Variablefunctions Internal(built-​in)functions Anonymousfunctions ArrowFunctions Firstclasscallablesyntax



請為這篇文章評分?