How do I get around a lack of constructors in CFCs?
A widely adopted practice is to create an "init" method that returns the object.
Example:
<cffunction name="init" access="public" output="false">
<cfreturn this />
</cffunction>
</cfcomponent>
The init method can accept arguments and perform object initialization, if needed. Now, you can always create your objects like this:
This question was written by Hal Helms.
It was last updated on June 12, 2006 at 5:13:04 PM EDT.
CFML Referenced
Categories
Comments
Comment made by JAlpino on October 19, 2006 at 4:49 PM
Correct me if I'm wrong, but I beleive that CFC's have 'pseudo' constructors in that any code written outside of a <cffunction> within the <cfcomponent> block is executed apon object instantiation.
So for example, if you wanted to read in a properties file to set some component variable when your object was created, you could do something like the following:
<cfcomponent name="myObj">
<!--- Pseudo constructor ---> <cfset variables.test = "testing"> <cftry> <cffile action="read" file="#expandPath('property.txt')#" variable="myvar"> <cfset variables.test = myvar> <cfcatch> <cfrethrow/> </cfcatch> </cftry>
<!--- Method to return 'test' variable ---> <cffunction name="printTest" returnType="string" output="false"> <cfreturn variables.test /> </cffunction>
</cfcomponent>
...
<cfset myObj = createObject("component","myObj")> <cfoutput>#myObj.printTest()#</cfoutput>
Comment made by Raymond Camden on October 19, 2006 at 4:51 PM
You are right - but - we do not recommend this practice. As stated in the article, the use of Init is considered best practice by the majority of CF developers.