CHAPTER 15 – Global Variables
You might want to use global C variables in your extension, either for your own internal use or for receiving php.ini values of your extension's registered INI directives (INI is discussed in the next section). As PHP is designed to run in multi-threaded environments, you shouldn't define global variables on your own. PHP supplies a mechanism that creates global variables for you, which can be used both in threaded and non-threaded environments. You should always use this mechanism and not define your own global variables. These global variables are then accessed via a macro and used just as if they are reg- ular global variables. The ext_skel script that created your skeleton myfile project created the necessary code to support global variables. By examining php_myfile.h, you should see a commented section similar to the following:
ZEND_BEGIN_MODULE_GLOBALS(myfile) int global_value; char *global_string; ZEND_END_MODULE_GLOBALS(myfile) You can uncomment this section and add any global variables you'd like in between the two macros. A few lines down in the file, you'll see that the skeleton script automatically defined a MYFILE_G(v) macro. This macro should be used all over your source code to access these global variables. It will make sure that if you're in a multi-threaded environment, it will access a per-thread copy of these globals. No mutual exclusion is required by you. The last thing you need to do in order for the global variables to work is to uncomment the following line in myfile.c: ZEND_DECLARE_MODULE_GLOBALS(myfile) You might want to initialize your global variables to a default value at the beginning of each PHP request. In addition, if for example, the global vari- ables point to allocated memory, you might also want to free the memory at the end of each request. For this purpose, the global variable mechanism sup- ports a special macro that allows you to register a constructor and destructor function for your global variables (see Table 15.8 for an explanation of its parameters): ZEND_INIT_MODULE_GLOBALS(module_name, globals_ctor, globals_dtor) Table 15.8 ZEND_INIT_MODULE_GLOBALS Macro Parameters Parameter Meaning module_name The name of your extension as passed to the ZEND_BEGIN_MODULE_GLOBALS() macro. In our case, myfile. globals_ctor The constructor function pointer. In the myfile extension, the function prototype would be something like void php_myfile_init_globals(zend_myfile_globals *myfile_globals) globals_dtor The destruction function pointer. For example, void php_myfile_init_globals(zend_myfile_globals *myfile_globals) You can see an example of the constructor function and use of the ZEND_INIT_MODULE_GLOBALS() macro in myfile.c.