7

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

欢迎提供其他最佳实践建议。自从我这样做以来已经有一段时间了。提前致谢。

4

4 回答 4

14

在 ColdFusion 组件中,所有公共名称都在This范围内,所有私有名称都在Variables范围内。名称可能包括“普通”变量属性以及“UDF”方法。在 ColdFusion 组件中,ThisVariables范围是每个实例的,并且不在实例之间共享。

This在 ColdFusion 组件之外,您可以使用结构表示法使用任何公共名称(在范围内的组件内可用的名称)。您不得访问任何私人名称。

默认范围始终是Variables- 在组件内、组件外、UDF 内、组件方法内等。

请注意,没有“内存”范围之类的东西。有命名范围,但没有内存范围。

于 2009-12-17T20:23:25.277 回答
7

是的,它是默认的变量范围。

<cfcomponent output="false">
    <cfset variables.mode = "development">

    <cffunction name="getMode" output="false">
        <cfreturn variables.mode>
    </cffunction>
</cfcomponent>

在 CFC 的 cffunctions 中限定所有变量的范围是一个好主意。

不要忘记 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>
于 2009-12-17T20:18:31.977 回答
3

我可能必须回答我自己的问题,以便下次在 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>
于 2009-12-17T20:09:34.773 回答
1
<cfcomponent>
<cfset this.mode = "development">
</cfcomponent>

调用页面:

<cfset c = createObject("component","myComponent")>
<cfoutput>
#c.Mode#
</cfoutput>
于 2009-12-19T19:30:24.257 回答