I’m taking this out of the other thread, as it’s off topic.
Sometimes a method is unrelated to an object, it’s related to the class. A fairly common situation is to have a static factory method that creates an instance of an object via a non-standard mechanism, eg:
// Person.cfc
component {
function init(firstName, lastName) {
variables.firstName = arguments.firstName
variables.lastName = arguments.lastName
}
function getFullName() {
return "#firstName# #lastName#"
}
static function createFromArray(nameParts) {
return new Person(nameParts[1], nameParts[2])
}
}
<!--- test.cfm --->
<cfscript>
ben = Person::createFromArray(["Ben", "Nadel"])
writeOutput(ben.getFullName())
</cfscript>
// output
Ben Nadel
One doesn’t want to mess with the constructor: it’s fine. One also doesn’t want to rejig the code so an “empty” Person can be created and then somehow poke the name parts into it. One wants a function that facilitates creating the object via a different mechanism.
I’ve kept the mechanism very simple and generic here, because if the inputs drifted too far into some bespoke approach, the factory method would probably cease belonging to Person, and best be put somewhere else (or in a proper PersonFactory class). I think an array is general enough for this to be legit. One could perhaps implement it as fromArray
instead. Still a class method, not an object one though.
It simply doesn’t make sense to implement createFromArray
/ fromArray
as an object method. There is no object.