If you're writing a script to be directly accessed by the web browser (e.g. /course/view.php), then you: require_once(__DIR__'/../../config.php'); at the top of it to include all the core Moodle code.
If you're writing a script that should only be called from Moodle core (e.g. an observer, that will be called internally by other Moodle code), then you start the file with: defined('MOODLE_INTERNAL')||die(); to make sure the script can only be called once the rest of Moodle has already been included.
If you want to use $DB in a function, then, just as it says in the parts of the docs you've shown, you write: global $DB; at the top of your function.
Observer functions must be static, so that they can be called statically by the Moodle code.