Tomalak's answer is correct for ColdFusion 8; however things are changing a little bit with ColdFusion 9, due out later this year. (For the sake of completeness, I'll copy in Tomalak's answer and adjust as appropriate, so thanks for the head start. :))
Must I use the name init as the constructor name?
CF8: No, you can name the initialization function anything you like -- "init" is merely a convention. And it is not a true constructor, since it is not automatically called.
CF9: The answer is still "no," you don't have to. But it may behoove you to: This applies to creating objects within cfscript (or script-only components, which are also coming in CF9). The import
and new
keywords are being added, and you will be able to create an instance of an object like so:
import model.security.*;
userObj = new User();
This assumes that you have a User.cfc
inside the model/security/
folder. In addition, CF9 will look for the existence of either a method named "init" or one with the same name as the object ("User", in this case), and implicitly call this as the constructor.
I'm not sure if passing in arguments to the new
directive will forward them on to the constructor as you would see in Java/C. I assume it will, but I haven't seen any presentations or code examples that indicate one way or the other, yet; and haven't tested it myself because it just occurred to me while writing this. ;) (Another idea: I wonder if multiple constructors with different argument-sets will be supported. I doubt it, but it's a neat idea.)
I assume there is some implication that similar functionality might show up in CFML (the tag-based language, separate from cfscript), but nothing has been said about that at this point.
If I create an instance of the component without invoking the init method, what is returned?
The component instance is returned, as you'd expect it. The presence or absence of an init() function is completely irrelevant. There is no notion of static functions in ColdFusion components, you always get a fully constructed instance from GetObject("component", ...). (Not so for Java objects, which are constructed just before first use, if you forgot to/did not do it manually.)
Can I take the code in the init method out and delete the init method, then paste the code to the head of the component, is it have a same effect as the init constructor?
Yes, as long as the init() method did not take any parameters, there is no difference.
However, it is a convention to have a method called init() that returns the component instance ("this"). Even if it does nothing apart from "return this;
". I'd stay consistent and add one to every component, even if it was not strictly necessary.