The Dopefly Tech Blog

« The Dopefly Tech Blog Main page

Fun with Functions and CFCs II - Object Hacking, There Is No Privacy

posted under category: ColdFusion on December 11, 2007 by Nathan

There are a lot of fun and interesting things you can do with ColdFusion components that languages like Java just don't let you. This is part 2 in my series to explore the interesting things that you can do with ColdFusion components and functions.

Before we begin, let's make a test CFC - here's the one I'm using; Test.cfc:
<cfcomponent>

  <cffunction name="init" access="public">
    <cfreturn this />
  </cffunction>

  <cffunction name="privateMethod" access="private">
    <cfreturn "This is a Private Method!" />
  </cffunction>

  <cffunction name="publicMethod" access="public">
    <cfreturn "This is a Public Method!" />
  </cffunction>

</cfcomponent>

Now we'll make an instance of it in a plain-jane .cfm file:
<cfset myCFC = createObject("component","Test").init()>

Now here comes the fun part. I want to get and execute the private method from the .cfm page. Not allowed, right? Not exactly. let's make a free-floating function in my .cfm file (this could be done with a cffunction tag, but I like the familiar script syntax):
<cfscript>
  function getCurrentVariables() {return variables;}
</cfscript>

If I call getCurrentVariables() now, it will return the current document's variables scope, which consists of a reference to that function and to my CFC instance's this scope, but what if I put that function onto my test CFC's public interface?

<cfset myCFC.getVariables = getCurrentVariables />

now, myCFC.getVariables() gives me the variables scope of the CFC! if I dump myCFC.getVariables(), I can see everything that's going on inside. Woah, now I can play with the internals all I want.

#myCFC.getVariables().privateMethod()# returns "This is a Private Method!"

Nathan is a software developer at The Boeing Company in Charleston, SC. He is essentially a big programming nerd. Really, you could say that makes him a nerd among nerds. Aside from making software for the web, he plays with tech toys and likes to think about programming's big picture while speaking at conferences and generally impressing people with massive nerdiness and straight-faced sarcastic humor. Nathan got his programming start writing batch files in DOS. It should go without saying, but these thought and opinions have nothing to do with Boeing in any way.
This blog is also available as an RSS 2.0 feed. Click your heels together and click here to contact Nathan.