ColdFusion 9 Dynamic Method Call

空扰寡人 提交于 2019-11-28 01:12:39

问题


I am trying to work out the correct <cfscript> syntax for calling a dynamic method within ColdFusion 9. I have tried a number of variations and had a good search around.

<cfinvoke> is clearly the tag I want, sadly however I cannot use this within my pure cfscript component as it was implemented in ColdFusion 10.

i.e coldfusion 9 dynamically call method

I have tried the following within my CFC:

/** Validate the method name **/
var resources = getResources();
if (structKeyExists(variables.resources, name)) {
  variables.resourceActive[name] = true;
  var reflectionMethod = resources[name];
  var result = "#reflectionMethod.getMethodName()#"(argumentCollection = params);
}

Where the return value of reflectionMethod.getMethodName() is the method name I want to call. It is 100% returning the correct value (the name of the method) where that method is correctly defined and accessible,

My error is a syntax error on that line.


回答1:


You don't want to get the method name, you want to get the actual method, eg something like:

function getMethod(string method){
    return variables[method];
}

The call that, thus:

theMethod = getMethod(variableHoldingMethodName);
result = theMethod();

Unfortunately one cannot simply do this:

result = getMethod(variableFoldingMethodName)();

Or:

result = myObject[variableFoldingMethodName]();

As the CF parser doesn't like the double-up of the parentheses or brackets.

The caveat with the method I suggested is that it pulls the method out of the CFC, so it will be running in the context of the calling code, not the CFC instance. Depending on the code in the method, this might or might not matter.

Another alternative is to inject a statically-named method INTO the object, eg:

dynamicName = "foo"; // for example
myObject.staticName = myObject[dynamicName];
result = myObject.staticName(); // is actually calling foo();



回答2:


Assuming the method is in your current (variables) scope, you could try:

var result = variables[reflectionMethod.getMethodName()](argumentCollection = params);


来源:https://stackoverflow.com/questions/12631347/coldfusion-9-dynamic-method-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!