How to write PHP extensions
By Justin Silverton
What is a php extension?
A PHP extension is a way to write extensions for the php language that would otherwise not be practical in the php language itself. The main benefit is speed of execution. An extension can be created in a compiled language such as c/c++ (if you look in your php.ini file, you can see examples of many extensions you most likely have already used) and loaded through a .dll (in windows) or a .so (in *nix) environment.
Types of extensions
Zend extensions
- pros: very fast and built into the core zend engine, which is what php runs on. This type of extension would be an actual change to the php interpreter/language (objects, expressions, etc).
- cons: if written improperly, can cause instability. These extensions are not recommended in most situations.
External extensions
- pros: Loaded at run-time (only the extension needs to be re-compiled when you make a change). Functionality is available to the script that loads it and memory is freed when the script ends.
- cons: Loading and unloading of extension may take up more processing power depending on how often the script loading it is accessed.
Built-in extensions
- pros: compiled with php and loaded with the php processes.
- cons: any changes to the extension require a complete re-compilation of php.
Example Code
An example extension project can be downloaded here
This example is for the *nix platform.
How to build:
$ phpize
$ ./configure –enable-hello
$ make
After running the above commands, you should have a hello.so file in ext/hello/modules/ . Now, you can copy this to your extensions directory (/usr/local/lib/php/extensions/ is the default, check your php.ini to be sure) and add the line extension=hello.so to your php.ini to trigger it to load on startup.
More in-depth information can be found here
No comments yet. Be the first.
Leave a reply





