Function arguments - Manual - PHP
文章推薦指數: 80 %
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. ...
延伸文章資訊
- 1Python Function Arguments (Default, Keyword and Arbitrary)
In Python, you can define a function that takes variable number of arguments. In this article, yo...
- 2JavaScript Function Parameters - W3Schools
Function parameters are the names listed in the function definition. Function arguments are the r...
- 3Argument of a function - Wikipedia
- 4Day18-Function-Argument語法糖 - iT 邦幫忙
關於function的 arguments ,也就是使用function時帶入的東西,有三種語法糖可以使用。 Default Argument Values; Keyword Arguments...
- 5Function arguments - Manual - PHP
Default argument values ¶. A function may define default values for arguments using syntax simila...