Skip to main content
Inspiring
October 22, 2007
Question

declaring a variable in CF

  • October 22, 2007
  • 2 replies
  • 435 views
I thought when a variable is needed, CF developer can just set it on the fly, <cfset var MyVar="assign a value here">
I'm writing a simple UDFs, and did not declare a variable. The error I got was Variable is undefined. Should I declared the variable when it is used within a function?

<cffunction name="InUser">
<cfargument name="EmpID" required="true" type="numeric">
<cfargument name="DeptArray" required="true" type="array">

<cfset NewUserID = 0> ----????????? If Omitted this, I got error saying NewUserID is Undefined.
.
.
.
<CFSET NewUserID = GetNewUser(UserName)>
.
.
Then I use the value of NewUserID for something else down here.
.
.

</cffunction>

<cffunction name="GetNewUser">
select statement to get userID based on userName

<CFRETURN #GetID.UserID#>
</cffunction>



This topic has been closed for replies.

2 replies

Inspiring
October 22, 2007
mega_L
> I thought when a variable is needed, CF developer can just set it on the fly

You can


mega_L
> Should I declared the variable when it is used within a function?

Technically you can use variables without declaring them. But with functions its best to declare local variables using the keyword VAR to prevent potential conflicts with other threads.

<cfset VAR NewUserID = 0>
...
<cfset NewUserID = GetNewUser(UserName)>


mega_L
> I'm writing a simple UDFs, and did not declare a variable. The error I got was Variable
> is undefined.
...

That suggests a problem in your code. Perhaps the GetNewUser() function does not return a value, or you've used the variable out of scope or before it was initialized.

mega_LAuthor
Inspiring
October 22, 2007
Thank you so much for the inpu!
Inspiring
October 22, 2007
Yes, and you should use the keyword "var" to keep it local to the function.