User Guide

Table Of Contents
218 Chapter 10: Building and Using ColdFusion Components
Instantiating CFCs
If you use a CFC multiple times in a ColdFusion request, or if you use a CFC with persistent
properties, use the
cfobject tag or CreateObject function to instantiate the CFC before you
call its methods.
The following example uses the
cfobject tag to create an instance of the tellTime CFC.
<cfobject component="tellTime" name="tellTimeObj">
The following example uses the CreateObject function to instantiate the same component in
CFScript:
tellTimeObj = CreateObject("component", "tellTime");
Invoking CFC methods with the cfinvoke tag
The
cfinvoke tag can invoke methods on a CFC instance or invoke CFC methods transiently.
You can also use the
cfinvoke tag to invoke CFC methods from within a CFC.
Invoking methods of a CFC instance
To invoke a component method of a CFC instance, use the
cfinvoke tag and specify the
following:
The CFC instance name, enclosed in number signs (#), in the component attribute.
The method name, in the method attribute.
Any parameters. For information on passing parameters, see “Passing parameters to methods
using the cfinvoke tag” on page 225.
If the component method returns a result, the name of the variable that will contain the result
in the
returnVariable attribute.
To invoke a method of a component instance using the cfinvoke tag:
1.
Create a file named tellTime2.cfc with the following code:
<cfcomponent>
<cffunction name="getLocalTime" access="remote">
<cfreturn TimeFormat(now())>
</cffunction>
<cffunction name="getUTCTime" access="remote">
<cfscript>
serverTime=now();
utcTime=GetTimeZoneInfo();
utcStruct=structNew();
utcStruct.Hour=DatePart("h", serverTime);
utcStruct.Minute=DatePart("n", serverTime);
utcStruct.Hour=utcStruct.Hour + utcTime.utcHourOffSet;
utcStruct.Minute=utcStruct.Minute + utcTime.utcMinuteOffSet;
if (utcStruct.Minute LT 10)
utcStruct.Minute = "0" & utcStruct.Minute;
</cfscript>
<cfreturn utcStruct.Hour & ":" & utcStruct.Minute>
</cffunction>
</cfcomponent>
The example defines two component methods: getLocalTime and getUTCTime.