Sam Farmer

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

But I have become passionate about making software.

Using StructKeyExists to find if an object has a function

December 15, 2009
Recently I have needed to dynamically know if an object has a public function. I found this can be achieved using structKeyExists. First, lets set up a cfc:
component accessors="true"
property name="firstname";
property name="age";
private function getaddress() {
            return variables.address;
private function setaddress( address ) {
            variables.address = arguments.address;
Or if you prefer a tag based cfc:
<cfcomponent accessors="true">
<cfproperty name="firstname">
<cfproperty name="age">
<cffunction name="getaddress" access="private">
            <cfreturn variables.address>
<cffunction name="setaddress" access="private">
            <cfset variables.address = arguments.address>
An object of this cfc will have 6 functions, 4 public ( getFirstname(), setFirstname(), getAge(), setAge() ) and 2 private ( getAddress(), setAddress() ).
Now based on getting errors when leaving off the parenthesis from a function call, I thought I would try and see if I could use structKeyExists to test if a function exists.
<cfset s = new Sample()>
<cfif structKeyExists( s, "setFirstname" )>
            The function setFirstname EXISTS!!<br>
            The function setFirstname can not be accessed or does not exist<br>
<cfif structKeyExists( s, "setAddress" )>
            The function setAddress EXISTS!!<br>
            The function setAddress can not be accessed or does not exist<br>
This will output:
The function setFirstname EXISTS!!
The function setAddress can not be accessed or does not exist
I was a little surprised it worked and can’t decide if its hackey or cool (or if hackey is even a word!). Next up I’ll show why I wanted to do this and use it dynamically.

No Comments

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


More blog entries that I have written.

Code coloring by PRISM.