Chapter 8. Writing PHP Extensions


  • Setting up a new PHP extension project

  • Adding functions to extensions

  • Dealing with variables from PHP

  • Using hash tables and arrays

  • Accessing MySQLi query results

  • Defining an object

  • Defining an interface

  • Providing more information about an extension

Sometimes pure PHP is not enough. Most commonly, this happens when speed is an issue or integration with a third-party non-PHP library is necessary. Writing extensions is also very useful for creating persistent resources.

This chapter builds a fully functional PHP extension that works with MySQLi Result objects and also performs various tasks relating to each type of data. It is intended for demonstration purposes only, but it works well and can be a good starting point for a custom extension.

This chapter assumes an intermediate understanding of the C language. Particular skill sets that are useful include pointers and memory allocation.


For many developers, one of the most frustrating parts about writing a PHP extension is simply that the extensions aren't written in PHP. Like MySQL UDFs, PHP extensions are also written in C. The C language doesn't have an automatic garbage collector, memory management, or any of the niceties of PHP so it can be much more difficult to work with. However, thanks to the Zend engine that powers PHP and the PHP engine itself, it maintains all the flexibility of PHP while adding the benefits of a lower-level language with direct ...

Get Expert PHP and MySQL® now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.