How to specify only some optional arguments when calling function in ColdFusion?
Solution 1
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) />
Solution 2
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)>
Solution 3
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>
Kip
I've been programming since I got my hands on a TI-83 in precalculus class during junior year of high school. Some cool stuff I've done: Chord-o-matic Chord Player: find out what those crazy chords are named! Everytime: keep track of the current time in lots of time zones from your system tray BigFraction: open source Java library for handling fractions to arbitrary precision. JSON Formatter: a completely client-side JSON beautifier/uglifier. QuickReplace: a completely client-side regex tool. It's behind some ugly developer UI since I created it for myself to use. (Sorry not sorry.)
Updated on June 09, 2022Comments
-
Kip almost 2 years
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 --->