CREATE STATIC

CREATE STATIC

These keywords, when placed alone at the beginning of a class file, tell the interpreter that when applying non-static symbols to the name of the class, an automatic hidden instance of it will be created on the fly.

If you use this feature, the class constructor (the special method _new) will be called with no parameters.

This feature is already used internally by the Form and the Settings classes.

Here is an excerpt of the Settings class code:

Example: Settings.class (gb.settings)

Export
Create Static

' ...

Public Sub _new(Optional Path As String, Optional Title As String)
  ' ...
    If Not Path Then
      Path = Settings.DefaultDir &/ Application.Name & ".conf"

Explanation

Consider this line of Gambas code:

Print Settings["Key"]

It looks like the array accessor method _get() is applied to the Settings class to get the value corresponding to the key "Key", but this doesn't make sense as the _get() method of Settings is not static but dynamic, i.e. it does not belong to the class but to some object of the class. But since Settings is CREATE STATIC, the interpreter will create the automatic instance of the Settings class behind the scenes and use this object for the array access.

The automatic instance of Settings is, as explained above, constructed without arguments. In the Settings.class code snippet above you see that in this case Path is set to the default configuration file path Settings.DefaultDir &/ Application.Name & ".conf".

In conclusion, whenever you use the class name "Settings" like an object (by using dynamic symbols on it), you actually use the hidden automatic instance of the Settings class, which is linked to the default configuration file.


[ASIDE] "Singletons"

This feature, together with CREATE PRIVATE, can be used to implement the object-oriented programming singleton pattern. CREATE STATIC allows you to use a class name like an object while CREATE PRIVATE makes the class uninstantiable (except for the automatic instance).

Instead of a CREATE STATIC + CREATE PRIVATE class you can also effectively use a module in Gambas!


See also