在Coldfusion组件/ CFC中,我想正确地将一些变量用于所有包含的函数,但要隐藏或阻止外部脚本。 cfc的内存范围是什么名字?这是'变量'吗?是否在包含的函数内可用?它是否被阻止在cfc之外?
(CF 8中的例子)
致电页面:
<cfset settings = structNew()>
<cfset util = createObject("component", "myUtils").init(settings)>
<cfoutput>
#util.myFunction()#
</cfoutput>
myUtils.cfc:
<cfcomponent>
<!--- Need to set some cfc global vars here --->
<cffunction name="init" access="public">
<cfargument name="settings" type="struct" required="no">
<!--- I need to merge arguments.settings to the cfc global vars here --->
<cfreturn this>
</cffunction>
<cffunction name="myFunction" access="public">
<cfset var result = "">
<!--- I need to access the cfc global vars here for init settings --->
<cfreturn result>
</cffunction>
</cfcomponent>
欢迎提供其他最佳做法建议。我做完这件事已经有一段时间了。提前谢谢。
答案 0 :(得分:14)
在ColdFusion组件中,所有公共名称都在This
范围内,所有私有名称都在Variables
范围内。名称可以包括“正常”变量属性以及“UDF”方法。在ColdFusion组件中,This
和Variables
范围是 per-instance ,并且不在实例之间共享。
在ColdFusion组件之外,您可以使用结构表示法使用任何公共名称(This
范围内的组件中可用的名称)。您可能无法访问任何私人名称。
默认范围始终为Variables
- 在组件内,组件外,UDF内,组件方法中等。
请注意,没有“内存”范围。有名为的范围,但没有内存范围。
答案 1 :(得分:7)
是的,它是默认的变量范围。
<cfcomponent output="false">
<cfset variables.mode = "development">
<cffunction name="getMode" output="false">
<cfreturn variables.mode>
</cffunction>
</cfcomponent>
最好将所有变量的范围放在CFC中的cffunction中。
不要忘记output =“false”,它会减少很多CF生成的空白。我通常会忽略access =“public”,因为这是默认值。
如果您想在其他人浏览您的CFC时获得更好的文档,您甚至可以考虑使用
<cfcomponent output="false">
<cfproperty name="mode" type="string" default="development" hint="doc...">
<cfset variables.mode = "development">
<cffunction name="getMode" output="false">
<cfreturn variables.mode>
</cffunction>
</cfcomponent>
答案 2 :(得分:2)
我可能不得不回答我自己的问题,这样下次我需要在StackOverflow上找到它。我不是积极的,但我认为这就是它的完成方式。 (一如既往,欢迎提出更正和建议!)
<cfcomponent>
<!--- Server Mode: production | development - used for differing paths and such --->
<cfset variables.mode = "development">
<cffunction name="init" access="public">
<cfargument name="settings" type="struct" required="no">
<cfset StructAppend(variables, arguments.settings)>
<cfreturn this>
</cffunction>
<cffunction name="getMode" access="public">
<cfreturn variables.mode>
</cffunction>
</cfcomponent>
致电页面:
<cfset c = createObject("component","myComponent").init()>
<cfoutput>
<!--- Should output "development" --->
#c.getMode()#
</cfoutput>
答案 3 :(得分:1)
<cfcomponent>
<cfset this.mode = "development">
</cfcomponent>
致电页面:
<cfset c = createObject("component","myComponent")>
<cfoutput>
#c.Mode#
</cfoutput>