Cheap and Easy Dynamic Method Calling in CFScript

For reasons I cannot entirely explain, I was trying to call dynamic methods in a cfc in cfscript. (The cfc code was calling a method within itself) I tested a few syntactically wrong ways of getting it done. It the underlying fact that functions are another type of variable in ColdFusion hit me. I should be able to assign dynamic variable to a new variable, and call that as a function. It worked.

<cfscript>

function test(input){
   
return input;
}

functionName = “test”;

args.input = “Yo!”;

tempfunc = variables[functionName];

output = tempfunc(argumentCollection = args);

writeOutput(output);

</cfscript>

I feel like someone must have done this before, but could find nothing on it. So I figured I would blog it.

10 thoughts on “Cheap and Easy Dynamic Method Calling in CFScript

  1. Looks good. I wish that we could do something like this:

    variables[ functionName ]();

    This works at a “functional” level (as it is what you are essentially doing); but, this fails to compile due to parsing issues.

    Like

  2. @Terrence, yeah, you are fine intra-cfc. I do this all the time when I don’t want to escape out of a cfscript block to use cfinvoke.

    Either that or when I pass a function to a function, as otherwise, for some reason cf throws a wobbly if you try and call arguments.foo(argumentCollection=args);

    Like

  3. It appears I’m late to the party on this one, but I have several methods in a CFC for saving form data. I was trying to create a single action page to call these save functions, but do so dynamically similar to what you’ve done here. I just used cfinvoke method=”#functionName#”. Is there a drawback to doing it this way with cfinvoke? Thanks for the great example!

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s