What is the equivalent of static methods in ColdFusion?

后端 未结 2 1645
有刺的猬
有刺的猬 2021-02-19 23:37

In C#, I created static methods to help me perform simple operations. For example:

public static class StringHelper
{
    public static string Reverse(string inp         


        
相关标签:
2条回答
  • 2021-02-20 00:13

    Nope, you are correct, there is no concept of static methods in ColdFusion. I think most would solve this problem through the use a singleton utilities in the application scope that are create when the application starts. So in your App.cfc in onApplication start you might have:

    <cfset application.StringHelper = createObject("component", "path.to.StringHelper") />
    

    Then when you needed to call it from anywhere you would use:

    <cfset reversedString = application.StringHelper.reverse(string) />
    

    Yeah, it's not as clean as static methods. Maybe someday we could have something like them. But right now I think this is as close as you will get.

    0 讨论(0)
  • 2021-02-20 00:15

    One way to create statics in ColdFuison is to put the function or variable in the metadata of the object. Its not perfect but like a static you don't have to create an instance of the object to call them and they'll last until the server is restarted so they are quite fast after the first call.

    Here's a quick snippet:

    component name="Employee"
    {
     public Employee function Init(){
      var metadata = getComponentMetaData("Employee"); 
    
      if(!structKeyExists(metadata,"myStaticVar")){
    
       lock name="metadata.myStaticVar" timeout="10"{
        metadata.myStaticVar = "Hello Static Variable."; 
       }
      }
    
      return this;
     }
    }
    

    More detail here: http://blog.bittersweetryan.com/2011/02/using-metadata-to-add-static-variables.html.

    0 讨论(0)
提交回复
热议问题