[AccessD] Using a static variable in a function to hold a class open

John Colby jwcolby at gmail.com
Fri Jun 24 07:39:12 CDT 2022


I have supervisor classes such as SysVars which have all the code and
variables to deal with some functionality, SysVars in this instance.  In
order to use the class, it needs to be initialized and held open for the
rest of eternity or at least until no longer needed.

I like to have a function to instantiate such a class, passing back the new
instance of the class.  This function can be used for referring to the
instance from then on, or to get a pointer to an instance that will be used
in several places.  By creating a static inside of the function, I can keep
the class instance alive, and yet not need a variable outside of the
function, and not have to have a term function to tear it back down.

Code that uses the class:
   cXMLHttp.MyInitMethod SomeParam, AnotherParam 'Init and pass back the
new instance pointer, then pass in parameters to MyInitMethod.
   cXMLHttp.SomeFunction SomeParam 'Pass back the existing pointer and do
something with the class

Notice that this syntax initializes the static variable the first time it
is called, passing back a pointer to the class.  The second and subsequent
times it simply passes back the already existing pointer to class.

In order to clean it up at the end, I have an optional param blnTerm
defaulting to false.  When it is time to clean up, I just call in to the
function passing true:

cleanup code somewhere:

cXMLHTTP True 'Set the static pointer to nothing

Function cXMLHTTP(Optional blnTerm As Boolean = False) As clsXMLHttp
Static lclsXMLHttp As clsXMLHttp

    If blnTerm Then
        Set lclsXMLHttp = Nothing
    Else
        If lclsXMLHttp Is Nothing Then
            Set lclsXMLHttp = New clsXMLHttp
        End If
        Set cXMLHTTP = lclsXMLHttp
     End If
End Function

-- 
John W. Colby
Colby Consulting


More information about the AccessD mailing list