Accessing public-private access through component inheritance in ColdFusion

I am having an unexpected problem with the ColdFusion markup language. Let's say I have the following components. If both public and private functions are defined in the "base" component, can the former still call the private when called from expanding instances of type "sub"?

Program.cfc

<cfcomponent>

    <cffunction access="public" name="doOperation"> 
        <cfset this.checkValue(-14)>
    </cffunction> 


    <cffunction access="private" name="checkValue">
        <cfargument name="notNeg" required="yes" type="numeric">

        <cfif arguments.notNeg LT 0 >
            <cfthrow message="Negative Numbers not allowed"> 
        </cfif>
    </cffunction> 

 </cfcomponent>

      

SubProgram.cfc

<cfcomponent extends="Program">

</cfcomponent>

      

Run.cfm

 <cfobject component="SubProgram" name="this.instance">

 <cfset this.instance.doOperation()>                      <<<<----ERROR---->>>>

      

ColdFusion throws an error

method checkValue

not found in component SubProgram

. Make sure the method is defined ...

What is the problem? No points of error for encapsulation!

+3


source to share


1 answer


The problem is when you are trying to call the method checkValue()

as a public method. this

does not work in CFML the same way it does in other languages ​​(very bad design decision on the part of Macromedia): this

is an external reference to the object itself, so if you call this.someMethod()

that tries to call a method public

called someMethod()

(as if you were calling myObject.someMethod()

). In CFML, a scope variables

is a private data / member reference.

What do you want to do:

<cffunction access="public" name="doOperation"> 
    <cfset variables.checkValue(-14)>
</cffunction> 

      



Or simply:

<cffunction access="public" name="doOperation"> 
    <cfset checkValue(-14)>
</cffunction> 

      

Also, if you are using the latest CF version (ex: CF10 or CF11), you really don't want to write your components in tags. This makes for some pretty awful code. Try to restrict the use of tags for viewing files. CF10 still doesn't support 100% of all CFML constructs in a script, but CF11 does.

+4


source







All Articles