ColdFusion 9 动态方法调用 [英] ColdFusion 9 Dynamic Method Call

查看:18
本文介绍了ColdFusion 9 动态方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出正确的 <cfscript> 语法,以便在 ColdFusion 9 中调用动态方法.我尝试了许多变体并进行了很好的搜索.

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> 显然是我想要的标签,但遗憾的是我不能在我的纯 cfscript 组件中使用它,因为它是在 ColdFusion 10 中实现的.

<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.

coldfusion 9动态调用方法

我在我的 CFC 中尝试了以下方法:

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);
}

其中reflectionMethod.getMethodName()的返回值就是我要调用的方法名.它是 100% 返回正确的值(方法的名称),其中该方法被正确定义和访问,

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.

推荐答案

你不想获取方法name,你想获取实际方法,例如:

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];
}

这样的调用:

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

不幸的是,不能简单地这样做:

Unfortunately one cannot simply do this:

result = getMethod(variableFoldingMethodName)();

或者:

result = myObject[variableFoldingMethodName]();

因为 CF 解析器不喜欢双括号或方括号.

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

我建议的方法需要注意的是,它将方法从 CFC 中提取出来,因此它将在调用代码的上下文中运行,而不是在 CFC 实例中运行.根据方法中的代码,这可能重要也可能不重要.

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();

这篇关于ColdFusion 9 动态方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆