Sam Farmer

Growing up I never imagined I would play bass guitar for the Dave Matthews Band. And indeed it never happened.

10 Little Ones: What are Implicit Accessors?

June 11, 2012

ColdFusion 10 added implicit accessors and in this post I'll cover how to turn them on and use them.

Turning on implicit accessors is achieved via a straightforward setting in application.cfc:
component { this.name = "implicitFun"; this.invokeImplicitAccessor = true; }

Once on this means we can now access a getter and setter function of an object/cfc using the same syntax as if it where a struct. Let's look at a simple component called user.cfc:
component accessors="true" { property firstname; property lastname; function getFirstname() { return UCase( variables.firstname ); } function getName() { return variables.firstname & " " & variables.lastname; } }

Now let's see what happens when we make an object and start interacting with it:
//using the automatic constructor -- there is no init //function in user user = new user( firstname="Homer", lastname="Simpson" ); //calling firstname will run getter function //in CF9 this was user.getFirstname() writeOutput( user.firstname ); /*DISPLAYS: HOMER */ //calling name which directly references variables scope does //not call getter function writeOutput( user.name ); /*DISPLAYS: Homer Simpson */ //now lets change the name and call it again: user.firstname = "Lisa"; writeOutput( user.firstname ); /*DISPLAYS: LISA */

As you can see from the code above when you call the implicit accessor on an object it calls the getter or setter function but within a cfc calling the variables scope directly calls the variable and not the getter or setter function.


No Comments

Some comments have been lost over the years due to moving hosts.

More


More blog entries that I have written.

Code coloring by PRISM.