I’m writing a function that loops through some info on a registration page. Within the loop I’m trying to call functions based on an array. What I’m having problems with is actually calling the functions properly, because I’m trying to incorporate a variable as part of the function name.
Here’s my code:
<cfscript>
fields = arraynew(1);
fields[1] = 'r_email';
fields[2] = 'r_uname';
fields[3] = 'r_pass';
for(i = 1; i lte arraylen(fields); i = i + 1)
{
func = fields[i].split('r_');
func = 'validate_#func[2]#(#fields[i]#)';
}
</cfscript>
So, I have three functions: validate_email, validate_uname, validate_pass. If I throw in a writeoutput(), and attempt to output the results of the function, they do not work.
Here’s that code:
<cfscript>
fields = arraynew(1);
fields[1] = 'r_email';
fields[2] = 'r_uname';
fields[3] = 'r_pass';
for(i = 1; i lte arraylen(fields); i = i + 1)
{
func = fields[i].split('r_');
func = 'validate_#func[2]#(#fields[i]#)';
writeoutput('#func#');
}
</cfscript>
Now, I understand that when you’re using writeoutput(), and you’re calling a function, you need the hash symbol on either end. So, let’s say I write it like this:
writeoutput('#validate_#func[2]#(#fields[i]#)#');
It won’t work, because the second hash symbol cancels out the function call. This is how the function should ultimately look (email example):
writeoutput('#validate_email('email@site.com')#');
How can I replace ’email’ (#validate_email…) with the proper variable name, and still have the function work? I hope I’ve made this understandable!
Functions are variables too, so in the same way you can use bracket notation for arrays, structs, and scopes, you can use this to access dynamic variable names (and thus dynamic function names)
For example:
Well… not quite. Due to a bug in Adobe ColdFusion, that doesn’t work like that (though it does in other CFML engines, like Railo), and you have to split it into two lines, like this:
(This assumes both function and fields are in the
variablesscope, if they’re not you need to refer to whichever scope they’re in.)This method does have an issue if the function was in an object with state, it loses reference to those variables.
On CF10, there is the
invokefunction. Earlier versions of CF need to use thecfinvoketag.(As a side note, CF10 did add the inverse ability of referencing function results with bracket notation, i.e.
doSomething()[key]which comes in useful at times.)