To encapsulate the procedural C or C++ interface for use in PHP, this refers to process-oriented encapsulation. The meaning of encapsulating PHP extensions lies in the fact that PHP cannot directly use C functions, as it needs its own memory management methods and parameter management approaches. Therefore, a "one-to-one mapping" must be created between C code and PHP code for the functions and variables to be used. The encapsulation process can roughly be divided into six steps: 1. Include header files 2. Declare exported functions 3. Declare zend function blocks 4. Declare zend modules 5. Implement the get_module() function 6. Implement the exported functions
A simple example can be examined where the source files are test.h and test.cpp, which generate extern_test.so. This dynamic link library is then dynamically loaded by test.php.
*********************************************************
//test.h
#ifndef _EXTERN_TEST_H_
#define _EXTERN_TEST_H_
#include // Include header files, i.e., introduce required macros, API definitions, etc.
#ifdef __cplusplus
extern "C" {
#endif
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#ifdef __cplusplus
}
#endif
#define EXTERN_TEST_VERSTR "0.1.0"
ZEND_MINFO_FUNCTION(extern_test);
ZEND_FUNCTION(extern_test_func); // Declare exported function
#endif
************************************************************
//test.cpp
#include "test.h"
// Declare zend function block
zend_function_entry extern_test_functions[] = {
ZEND_FE(extern_test_func, NULL),
{ NULL, NULL, NULL }
};
// Declare zend module
zend_module_entry extern_test_module_entry = {
STANDARD_MODULE_HEADER,
"extern_test",
extern_test_functions,
NULL,
NULL,
NULL,
NULL,
ZEND_MINFO(extern_test),
EXTERN_TEST_VERSTR,
STANDARD_MODULE_PROPERTIES
};
// Implement get_module() function
#ifdef __cplusplus
BEGIN_EXTERN_C()
#endif
ZEND_GET_MODULE(extern_test)
#ifdef __cplusplus
END_EXTERN_C()
#endif
ZEND_MINFO_FUNCTION(extern_test) {
}
// Implement exported function
ZEND_FUNCTION(extern_test_func) {
int iInt = 0;
if (ZEND_NUM_ARGS() == 1) {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &iInt) == FAILURE) {
RETURN_LONG(ERR_PARAM_NUM);
}
} else {
RETURN_LONG(ERR_PARAM_NUM);
}
RETURN_LONG(iInt);
}
************************************************************
After executing the above PHP program, it will output “12345”.