Search code examples
asp-classicinclude

Asp Classic Include Once


Does ASP Classic have a feature that is the equivalent of PHP's "include once" feature?


Solution

  • I know this is an old topic, but I thought I'd add my two cents in case anyone's interested.

    I wrote a function that does precisely what you want: includes the given file exactly one no matter how many times it was called.

    class ImportFunction
        private libraries_
        private fso_
    
        private sub CLASS_INITIALIZE
            set libraries_ = Server.createObject("Scripting.Dictionary")
            set fso_ = Server.createObject("Scripting.FileSystemObject")
        end sub
    
        public default property get func (path)
            if not libraries_.exists(path) then
    
                on error resume next
                with fso_.openTextFile(path)
                    executeGlobal .readAll
                    if Err.number <> 0 then 
                        Response.write "Error importing library "
                        Response.write path & "<br>"
                        Response.write Err.source & ": " & Err.description
                    end if
                end with
                on error goto 0
    
                libraries_.add path, null
            end if
        end property
    end class
    dim import: set import = new ImportFunction
    

    Notes:

    • This uses a faux function simulated with a default property. If this bothers you, it's easily refactored.
    • The dictionary must be persistent through all includes, whereas persisting the fso merely avoids reconstructing it. If you don't like the idea of keeping them around after the imports are done, you could modify the class to get syntax like this:

      with new Importer
          .import "foo"
          .import "bar/baz"
      end with