我想轻松地将参数的结构内容放入组件的所有函数的变量范围中。 '名称'是searchitems结构之一。
<cffunction name="setSearch" acces="public" returntype="void">
<cfargument name="searchitems" type="struct" required="true" />
<cfset variables = arguments.searchitems>
<cfset variables.test = "yo">
</cffunction>
<cffunction name="testit" acces="public" returntype="void">
<cfdump var="#variables.test#"><br>
<cfif isdefined('variables.test')>found in variables.test </cfif>
<cfif isdefined('variables.variables.test')>found in variables.variables.test </cfif>
<hr>
<cfdump var="#variables.title#"><br>
<cfif structkeyexists(variables,'title')>found in variables.title with structkeyexists </cfif>
<cfif structkeyexists(variables.variables,'title')>found in variables.variables.title with structkeyexists</cfif>
<cfif isdefined('variables.title')>found in variables.title </cfif>
<cfif isdefined('variables.variables.title')>found in variables.variables.title</cfif>
</cffunction>
然而,运行它会给出:
yo
found in variables.test
mytitletext
found in variables.variables.title with structkeyexists
found in variables.variables.title
我发现这很奇怪,标题可以转储或输出为variables.title,但不能用isDefined或structkeyexists检测。是否有更有效的方式来分配
<cfset variables = arguments.searchitems>
答案 0 :(得分:2)
使用组件的“this”范围。
<cfcomponent>
<cfset this.myArgs = StructNew()>
<cfset this.test = "">
<cffunction name="setSearch" acces="public" returntype="void">
<cfargument name="searchitems" type="struct" required="true" />
<cfset this.myArgs= arguments>
<cfset this.test = "yo">
</cffunction>
</cfcomponent>
答案 1 :(得分:1)
我建议遵循Adam的建议,并将searchitems
保存在变量范围内的独立结构中,而不是单独的项目中。这样你就不会冒险覆盖其他变量。
<强> Test.cfc 强>
<cfcomponent>
<cffunction name="init">
<!--- Set up a separate empty container for the searchitems to be available to all functions --->
<cfset variables.searchitems = StructNew()>
<cfreturn this>
</cffunction>
<cffunction name="setSearch" returntype="void">
<cfargument name="searchitems" type="struct" required="true">
<!--- Fill the container with the struct passed into this function --->
<cfset variables.searchitems = arguments.searchitems>
</cffunction>
<cffunction name="dumpSearchTitle" returntype="void">
<cfdump var="#variables.searchitems.title#">
</cffunction>
</cfcomponent>
<强> index.cfm 强>
<cfscript>
request.searchitems = StructNew();
request.searchitems.title = "mytitletext";
test = CreateObject( "component", "test" );
test.setSearch( request.searchitems );
test.dumpSearchTitle();
</cfscript>
但是,如果在变量范围中包含单个searchitems
非常重要,那么您可以将它们附加到变量范围。 false
的第三个StructAppend
参数可确保您不会覆盖现有变量。
<强> Test.cfc 强>
<cfcomponent>
<cffunction name="init">
<cfreturn this>
</cffunction>
<cffunction name="setSearch" returntype="void">
<cfargument name="searchitems" type="struct" required="true">
<cfset StructAppend( variables,arguments.searchitems,false )>
</cffunction>
<cffunction name="dumpSearchTitle" returntype="void">
<cfdump var="#variables.title#">
</cffunction>
</cfcomponent>