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>
<cffunction name="setaddress" access="private">
<cfset variables.address = arguments.address>
</cffunction>
</cfcomponent>
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>
<cfelse>
The function setFirstname can not be accessed or does not exist<br>
</cfif>
<cfif structKeyExists( s, "setAddress" )>
The function setAddress EXISTS!!<br>
<cfelse>
The function setAddress can not be accessed or does not exist<br>
</cfif>
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.
Some comments have been lost over the years due to moving hosts.