Search code examples
coldfusionreturn-valuecoldfusion-11

CFSET Invoking Function without variable


New pretty new with this language, started code with it this week.

So my problem is the new company that I started with uses CF11 and they mainly only code with tags. I want to know if is possible to call cfset without a variable declaration.

If not what is the better way to call functions (that don't have return) with tags?

<cfset myFunction()>

I usually call my initiate functions at cfset, but they all have returning.

<cfset something = #initSomething()#>

Solution

  • Yes, invoking a function without capturing the result is perfectly fine. Sadly, there used to be a lot of that syntax in older CF documentation. It gave the erroneous impression you MUST capture the result of a function (and use extra pound signs everywhere). Neither is true. Even if a function does return something, you're not required to capture the result. Only if you wish to use it for something later. You're always free to invoke a function and completely ignore the result. So both of these are valid:

    <!--- 1. capture result ---> 
    <cfset result = getTimeNow()>
    <!--- 2. ignore result ---> 
    <cfset getTimeNow()>
    
    <!--- sample function --->
    <cffunction name="getTimeNow" return="date">
        <cfreturn now()>
    </cffunction>
    

    Technically, there's nothing stopping you from capturing the result of a function that doesn't return anything. However, the "result" variable will be undefined, so it really serves no purpose.

     <cfset result = doNothing()>
     <!--- this will error --->
     <cfoutput>#result#</cfoutput>
    
     <!--- sample function --->
     <cffunction name="doNothing" return="void">
        <!--- function that returns nothing --->
     </cffunction>