Implicit Conversion Functions

Following up with Magic Functions - Implicit Component Getters / Setters , there's one more gem. Again, this has been around since Lucee 2. We're going to make a new, yet similar example. This time, we're going to create an address object:


<cfcomponent output="false">
<cffunction name="init" access="public" returntype="address" output="false">
	<cfreturn this>
<cffunction name="setStreet1" access="public" returntype="void" output="false">
	<cfargument name="street" required="true" type="string" default="">
	<cfif len(arguments.street)>
		<cfset variables.street1 = arguments.street>
		<cfthrow message="Street 1 is required.">
<cffunction name="setCity" access="public" returntype="void" output="false">
	<cfargument name="city" required="true" type="string" default="">
		<cfif len(>
			<cfset =>
			<cfthrow message="City is required.">
<cffunction name="setState" access="public" returntype="void" output="false">
	<cfargument name="state" required="true" type="string" default="">
	<cfif len(arguments.state) EQ 2>
		<cfset variables.state = arguments.state>
		<cfthrow message="State is required and must be a 2 character length.">
<cffunction name="setPostalCode" access="public" returntype="void" output="false">
	<cfargument name="postalcode" required="true" type="string" default="">
	<cfif len(arguments.postalcode)>
		<cfset variables.postalcode = arguments.postalcode>
		<cfthrow message="Postal Code is required.">
<cffunction name="getStreet1" access="public" returntype="string" output="false">
	<cfreturn variables.street1>
<cffunction name="getCity" access="public" returntype="string" output="false">
<cffunction name="getState" access="public" returntype="string" output="false">
	<cfreturn variables.state>
<cffunction name="getPostalCode" access="public" returntype="string" output="false">
	<cfreturn variables.postalcode>
<cffunction name="_toString" access="public" returntype="string" output="false">
	<cfset var address = "">
	<cfsavecontent variable="address"><cfoutput>#getStreet1()#<br>#getCity()#, #getState()# #getPostalCode()#</cfoutput></cfsavecontent>
	<cfreturn address>


<cfset address = createObject('component','address').init()>
<cfset address.street1 = "Some Street">
<cfset = "Some City">
<cfset address.state = "CA">
<cfset address.postalcode = "12345">

Now, in the address.cfc, note that we have a new function named _toString - This is a special conversion/function method name.

There are other simple types available:

  • _toBoolean()
  • _toDate()
  • _toNumeric()
  • _toString()
  • _toJSON()

Now, let's look at the output of my address object:

Some Street
Some City, CA 12345

As you can see, the address object was converted to a string via the _toString function.

See also