Reputation: 109453
I have a ColdFusion function "foo" which takes three args, and the second two are optional:
<cffunction name="foo" access="public" returntype="any">
<cfargument name="arg1" type="any" required="true" />
<cfargument name="arg2" type="any" required="false" default="arg2" />
<cfargument name="arg3" type="any" required="false" default="arg3" />
...
<cfreturn whatever />
</cffunction>
I want to call foo, passing in arg1 and arg3, but leaving out arg2. I know that this is possible if I call the function using cfinvoke
, but that syntax is really verbose and complicated. I have tried these two approaches, neither works:
<cfset somevar=foo(1, arg3=3) /> <!--- gives syntax error --->
<cfset somevar=foo(1, arg3:3) /> <!--- gives syntax error --->
Upvotes: 18
Views: 11979
Reputation: 32915
Or.. you can use ArgumentCollection
In CF9 or above...
<cfset somevar = foo(argumentCollection={arg1=1, arg3=3})>
In CF8 or above...
<cfset args = {arg1=1, arg3=3}>
<cfset somevar = foo(argumentCollection=args)>
If CF7 or below...
<cfset args = structNew()>
<cfset args.arg1 = 1>
<cfset args.arg3 = 3>
<cfset somevar = foo(argumentCollection=args)>
Upvotes: 23
Reputation: 9
I too was looking for some answers as Kip posted. Following is what I implemented. Hope it could add to our chain of possible solutions. I just added <cfparam>
to the cffunction code:
<cffunction name="fn1" access="public" returntype="numeric">
<cfargument name="arg1" type="numeric" required="true">
<cfargument name="arg2" type="numeric" required="true">
<cfargument name="arg3" type="query" required="false">
<cfparam name="arguments.arg1" default=0>
<cfparam name="arguments.arg2" default=0>
<cfparam name="arguments.arg3" default=0>
<cfreturn arguments.arg1 + arguments.arg2 + arguments.arg3>
</cffunction>
<cfoutput>#fn1(arg1=1,arg2=2)#</cfoutput>
Upvotes: 0
Reputation: 59341
You have to use named arguments throughout. You can't mix named and positional arguments as you can in some other languages.
<cfset somevar = foo(arg1=1, arg3=3) />
Upvotes: 33
Reputation: 15484
if you use named args you have to name the first too
<cffunction name="foo" access="public" returntype="any">
<cfargument name="arg1" type="any" required="true" />
<cfargument name="arg2" type="any" required="false" default="arg2" />
<cfargument name="arg3" type="any" required="false" default="arg3" />
<cfreturn arg2 & " " & arg3>
</cffunction>
<cfset b = foo(arg1:1,arg3:2)>
<cfoutput>#b#</cfoutput>
Upvotes: 2