<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>Zend API: Hacking the Core of PHP</title> </head> <body><div class="manualnavbar" style="text-align: center;"> <div class="prev" style="text-align: left; float: left;"><a href="internals2.ze1.streams.html">Streams API for PHP Extension Authors</a></div> <div class="next" style="text-align: right; float: right;"><a href="internals2.ze1.tsrm.html">TSRM API</a></div> <div class="up"><a href="internals2.ze1.html">Zend Engine 1</a></div> <div class="home"><a href="index.html">PHP Manual</a></div> </div><hr /><div id="internals2.ze1.zendapi" class="sect1"> <h2 class="title">Zend API: Hacking the Core of PHP</h2> <div class="sect2" id="internals2.ze1.zendapi.intro"> <h3 class="title">Introduction</h3> <p class="para">Those who know don't talk.</p> <p class="para">Those who talk don't know.</p> <p class="para"/> <p class="para"> Sometimes, PHP "as is" simply isn't enough. Although these cases are rare for the average user, professional applications will soon lead PHP to the edge of its capabilities, in terms of either speed or functionality. New functionality cannot always be implemented natively due to language restrictions and inconveniences that arise when having to carry around a huge library of default code appended to every single script, so another method needs to be found for overcoming these eventual lacks in PHP. </p> <p class="para"> As soon as this point is reached, it's time to touch the heart of PHP and take a look at its core, the C code that makes PHP go. </p> <div class="warning"><strong class="warning">Warning</strong> <p class="para"> This information is currently rather outdated, parts of it only cover early stages of the ZendEngine 1.0 API as it was used in early versions of PHP 4. </p> <p class="para"> More recent information may be found in the various README files that come with the PHP source and the <a href="http://devzone.zend.com/public/view/tag/Extension" class="link external">» Internals</a> section on the Zend website. </p> </div> </div> <div class="sect2" id="internals2.ze1.zendapi.overview"> <h3 class="title">Overview</h3> <p class="para"> "Extending PHP" is easier said than done. PHP has evolved to a full-fledged tool consisting of a few megabytes of source code, and to hack a system like this quite a few things have to be learned and considered. When structuring this chapter, we finally decided on the "learn by doing" approach. This is not the most scientific and professional approach, but the method that's the most fun and gives the best end results. In the following sections, you'll learn quickly how to get the most basic extensions to work almost instantly. After that, you'll learn about Zend's advanced API functionality. The alternative would have been to try to impart the functionality, design, tips, tricks, etc. as a whole, all at once, thus giving a complete look at the big picture before doing anything practical. Although this is the "better" method, as no dirty hacks have to be made, it can be very frustrating as well as energy- and time-consuming, which is why we've decided on the direct approach. </p> <p class="para"> Note that even though this chapter tries to impart as much knowledge as possible about the inner workings of PHP, it's impossible to really give a complete guide to extending PHP that works 100% of the time in all cases. PHP is such a huge and complex package that its inner workings can only be understood if you make yourself familiar with it by practicing, so we encourage you to work with the source. </p> <div class="sect3" id="internals2.ze1.zendapi.overview.whatisit"> <h4 class="title">What Is Zend? and What Is PHP?</h4> <p class="para"> The name <em class="emphasis">Zend</em> refers to the language engine, PHP's core. The term <em class="emphasis">PHP</em> refers to the complete system as it appears from the outside. This might sound a bit confusing at first, but it's not that complicated ( <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.fig.internal-struct" class="link">see below</a>). To implement a Web script interpreter, you need three parts: <ol type="1"> <li class="listitem"> <p class="para"> The <em class="emphasis">interpreter</em> part analyzes the input code, translates it, and executes it. </p> </li> <li class="listitem"> <p class="para"> The <em class="emphasis">functionality</em> part implements the functionality of the language (its functions, etc.). </p> </li> <li class="listitem"> <p class="para"> The <em class="emphasis">interface</em> part talks to the Web server, etc. </p> </li> </ol> Zend takes part 1 completely and a bit of part 2; PHP takes parts 2 and 3. Together they form the complete PHP package. Zend itself really forms only the language core, implementing PHP at its very basics with some predefined functions. PHP contains all the modules that actually create the language's outstanding capabilities. <div class="mediaobject"> <div class="imageobject"> <img src="images/befd863081615f539082d9ff76bf7b39-zend.01-internal-structure.png" alt="The internal structure of PHP." width="617" height="281" /> </div> </div> </p> <p class="para"> The following sections discuss where PHP can be extended and how it's done. </p> </div> </div> <div class="sect2" id="internals2.ze1.zendapi.possibilities"> <h3 class="title">Extension Possibilities</h3> <p class="para"> As shown <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.fig.internal-struct" class="link">above</a>, PHP can be extended primarily at three points: external modules, built-in modules, and the Zend engine. The following sections discuss these options. </p> <div class="sect3" id="internals2.ze1.zendapi.possibilities.external"> <h4 class="title">External Modules</h4> <p class="para"> External modules can be loaded at script runtime using the function <span class="function"><a href="function.dl.html" class="function">dl()</a></span>. This function loads a shared object from disk and makes its functionality available to the script to which it's being bound. After the script is terminated, the external module is discarded from memory. This method has both advantages and disadvantages, as described in the following table: <table class="doctable informaltable"> <col style="width: *;" /> <col style="width: *;" /> <tbody class="tbody"> <tr> <td>Advantages</td> <td>Disadvantages</td> </tr> <tr> <td> External modules don't require recompiling of PHP. </td> <td> The shared objects need to be loaded every time a script is being executed (every hit), which is very slow. </td> </tr> <tr> <td> The size of PHP remains small by "outsourcing" certain functionality. </td> <td> External additional files clutter up the disk. </td> </tr> <tr> <td class="empty"> </td> <td class="empty"> </td><td> Every script that wants to use an external module's functionality has to specifically include a call to <span class="function"><a href="function.dl.html" class="function">dl()</a></span>, or the <em>extension</em> tag in <var class="filename">php.ini</var> needs to be modified (which is not always a suitable solution). </td> </tr> </tbody> </table> To sum up, external modules are great for third-party products, small additions to PHP that are rarely used, or just for testing purposes. To develop additional functionality quickly, external modules provide the best results. For frequent usage, larger implementations, and complex code, the disadvantages outweigh the advantages. </p> <p class="para"> Third parties might consider using the <em>extension</em> tag in <var class="filename">php.ini</var> to create additional external modules to PHP. These external modules are completely detached from the main package, which is a very handy feature in commercial environments. Commercial distributors can simply ship disks or archives containing only their additional modules, without the need to create fixed and solid PHP binaries that don't allow other modules to be bound to them. </p> </div> <div class="sect3" id="internals2.ze1.zendapi.possibilities.builtin"> <h4 class="title">Built-in Modules</h4> <p class="para"> Built-in modules are compiled directly into PHP and carried around with every PHP process; their functionality is instantly available to every script that's being run. Like external modules, built-in modules have advantages and disadvantages, as described in the following table: <table class="doctable informaltable"> <col style="width: *;" /> <col style="width: *;" /> <tbody class="tbody"> <tr> <td>Advantages</td> <td>Disadvantages</td> </tr> <tr> <td> No need to load the module specifically; the functionality is instantly available. </td> <td> Changes to built-in modules require recompiling of PHP. </td> </tr> <tr> <td> No external files clutter up the disk; everything resides in the PHP binary. </td> <td> The PHP binary grows and consumes more memory. </td> </tr> </tbody> </table> Built-in modules are best when you have a solid library of functions that remains relatively unchanged, requires better than poor-to-average performance, or is used frequently by many scripts on your site. The need to recompile PHP is quickly compensated by the benefit in speed and ease of use. However, built-in modules are not ideal when rapid development of small additions is required. </p> </div> <div class="sect3" id="internals2.ze1.zendapi.possibilities.engine"> <h4 class="title">The Zend Engine</h4> <p class="para"> Of course, extensions can also be implemented directly in the Zend engine. This strategy is good if you need a change in the language behavior or require special functions to be built directly into the language core. In general, however, modifications to the Zend engine should be avoided. Changes here result in incompatibilities with the rest of the world, and hardly anyone will ever adapt to specially patched Zend engines. Modifications can't be detached from the main PHP sources and are overridden with the next update using the "official" source repositories. Therefore, this method is generally considered bad practice and, due to its rarity, is not covered in this book. </p> </div> </div> <div class="sect2" id="internals2.ze1.zendapi.layout"> <h3 class="title">Source Layout</h3> <blockquote class="note"><p><strong class="note">Note</strong>: <p class="para"> Prior to working through the rest of this chapter, you should retrieve clean, unmodified source trees of your favorite Web server. We're working with Apache (available at <a href="http://httpd.apache.org/" class="link external">» http://httpd.apache.org/</a>) and, of course, with PHP (available at <a href="http://www.php.net/" class="link external">» http://www.php.net/</a> - does it need to be said?). </p> <p class="para"> Make sure that you can compile a working PHP environment by yourself! We won't go into this issue here, however, as you should already have this most basic ability when studying this chapter. </p> </p></blockquote> <p class="para"> Before we start discussing code issues, you should familiarize yourself with the source tree to be able to quickly navigate through PHP's files. This is a must-have ability to implement and debug extensions. </p> <p class="para"> The following table describes the contents of the major directories. </p> <table class="doctable informaltable"> <col style="width: 1.00*;" /> <col style="width: 3.74*;" /> <tbody class="tbody"> <tr> <td>Directory</td> <td>Contents</td> </tr> <tr> <td><var class="filename">php-src</var></td> <td> Main PHP source files and main header files; here you'll find all of PHP's API definitions, macros, etc. (important). Everything else is below this directory. </td> </tr> <tr> <td><var class="filename">php-src/ext</var></td> <td> Repository for dynamic and built-in modules; by default, these are the "official" PHP modules that have been integrated into the main source tree. From PHP 4.0, it's possible to compile these standard extensions as dynamic loadable modules (at least, those that support it). </td> </tr> <tr> <td><var class="filename">php-src/main</var></td> <td> This directory contains the main php macros and definitions. (important) </td> </tr> <tr> <td><var class="filename">php-src/pear</var></td> <td> Directory for the PHP Extension and Application Repository. This directory contains core PEAR files. </td> </tr> <tr> <td><var class="filename">php-src/sapi</var></td> <td> Contains the code for the different server abstraction layers. </td> </tr> <tr> <td><var class="filename">TSRM</var></td> <td> Location of the "Thread Safe Resource Manager" (TSRM) for Zend and PHP. </td> </tr> <tr> <td><var class="filename">ZendEngine2</var></td> <td> Location of the Zend Engine files; here you'll find all of Zend's API definitions, macros, etc. (important). </td> </tr> </tbody> </table> <p class="para"> Discussing all the files included in the PHP package is beyond the scope of this chapter. However, you should take a close look at the following files:<ul class="itemizedlist"> <li class="listitem"> <p class="para"> <var class="filename">php-src/main/php.h</var>, located in the main PHP directory. This file contains most of PHP's macro and API definitions. </p> </li> <li class="listitem"> <p class="para"> <var class="filename">php-src/Zend/zend.h</var>, located in the main Zend directory. This file contains most of Zend's macros and definitions. </p> </li> <li class="listitem"> <p class="para"> <var class="filename">php-src/Zend/zend_API.h</var>, also located in the Zend directory, which defines Zend's API. </p> </li> </ul> You should also follow some sub-inclusions from these files; for example, the ones relating to the Zend executor, the PHP initialization file support, and such. After reading these files, take the time to navigate around the package a little to see the interdependencies of all files and modules - how they relate to each other and especially how they make use of each other. This also helps you to adapt to the coding style in which PHP is authored. To extend PHP, you should quickly adapt to this style. </p> <div class="sect3" id="internals2.ze1.zendapi.layout.conventions"> <h4 class="title">Extension Conventions</h4> <p class="para"> Zend is built using certain conventions; to avoid breaking its standards, you should follow the rules described in the following sections. </p> </div> <div class="sect3" id="internals2.ze1.zendapi.layout.macros"> <h4 class="title">Macros</h4> <p class="para"> For almost every important task, Zend ships predefined macros that are extremely handy. The tables and figures in the following sections describe most of the basic functions, structures, and macros. The macro definitions can be found mainly in <var class="filename">zend.h</var> and <var class="filename">zend_API.h</var>. We suggest that you take a close look at these files after having studied this chapter. (Although you can go ahead and read them now, not everything will make sense to you yet.) </p> </div> <div class="sect3" id="internals2.ze1.zendapi.layout.memory-management"> <h4 class="title">Memory Management</h4> <p class="para"> Resource management is a crucial issue, especially in server software. One of the most valuable resources is memory, and memory management should be handled with extreme care. Memory management has been partially abstracted in Zend, and you should stick to this abstraction for obvious reasons: Due to the abstraction, Zend gets full control over all memory allocations. Zend is able to determine whether a block is in use, automatically freeing unused blocks and blocks with lost references, and thus prevent memory leaks. The functions to be used are described in the following table: <table class="doctable informaltable"> <col style="width: 1.00*;" /> <col style="width: 1.62*;" /> <tbody class="tbody"> <tr> <td>Function</td> <td>Description</td> </tr> <tr> <td> <span class="function"><strong>emalloc()</strong></span></td> <td>Serves as replacement for <span class="function"><strong>malloc()</strong></span>.</td> </tr> <tr> <td> <span class="function"><strong>efree()</strong></span></td> <td>Serves as replacement for <span class="function"><strong>free()</strong></span>.</td> </tr> <tr> <td> <span class="function"><strong>estrdup()</strong></span></td> <td>Serves as replacement for <span class="function"><strong>strdup()</strong></span>.</td> </tr> <tr> <td> <span class="function"><strong>estrndup()</strong></span></td> <td>Serves as replacement for <span class="function"><strong>strndup()</strong></span>. Faster than <span class="function"><strong>estrdup()</strong></span> and binary-safe. This is the recommended function to use if you know the string length prior to duplicating it.</td> </tr> <tr> <td> <span class="function"><strong>ecalloc()</strong></span></td> <td>Serves as replacement for <span class="function"><strong>calloc()</strong></span>.</td> </tr> <tr> <td> <span class="function"><strong>erealloc()</strong></span></td> <td>Serves as replacement for <span class="function"><strong>realloc()</strong></span>.</td> </tr> </tbody> </table> <span class="function"><strong>emalloc()</strong></span>, <span class="function"><strong>estrdup()</strong></span>, <span class="function"><strong>estrndup()</strong></span>, <span class="function"><strong>ecalloc()</strong></span>, and <span class="function"><strong>erealloc()</strong></span> allocate internal memory; <span class="function"><strong>efree()</strong></span> frees these previously allocated blocks. Memory handled by the <span class="function"><strong>e*()</strong></span> functions is considered local to the current process and is discarded as soon as the script executed by this process is terminated. <div class="warning"><strong class="warning">Warning</strong> <p class="para"> To allocate resident memory that survives termination of the current script, you can use <span class="function"><strong>malloc()</strong></span> and <span class="function"><strong>free()</strong></span>. This should only be done with extreme care, however, and only in conjunction with demands of the Zend API; otherwise, you risk memory leaks. </p> </div> Zend also features a thread-safe resource manager to provide better native support for multithreaded Web servers. This requires you to allocate local structures for all of your global variables to allow concurrent threads to be run. Because the thread-safe mode of Zend was not finished back when this was written, it is not yet extensively covered here. </p> </div> <div class="sect3" id="internals2.ze1.zendapi.layout.dir-and-file"> <h4 class="title">Directory and File Functions</h4> <p class="para"> The following directory and file functions should be used in Zend modules. They behave exactly like their C counterparts, but provide virtual working directory support on the thread level. <table class="doctable informaltable"> <col style="width: *;" /> <col style="width: *;" /> <tbody class="tbody"> <tr> <td>Zend Function</td> <td>Regular C Function</td> </tr> <tr> <td> <span class="function"><strong>V_GETCWD()</strong></span></td> <td> <span class="function"><a href="function.getcwd.html" class="function">getcwd()</a></span></td> </tr> <tr> <td> <span class="function"><strong>V_FOPEN()</strong></span></td> <td> <span class="function"><a href="function.fopen.html" class="function">fopen()</a></span></td> </tr> <tr> <td> <span class="function"><strong>V_OPEN()</strong></span></td> <td> <span class="function"><strong>open()</strong></span></td> </tr> <tr> <td> <span class="function"><strong>V_CHDIR()</strong></span></td> <td> <span class="function"><a href="function.chdir.html" class="function">chdir()</a></span></td> </tr> <tr> <td> <span class="function"><strong>V_GETWD()</strong></span></td> <td> <span class="function"><strong>getwd()</strong></span></td> </tr> <tr> <td> <span class="function"><strong>V_CHDIR_FILE()</strong></span></td> <td> Takes a file path as an argument and changes the current working directory to that file's directory. </td> </tr> <tr> <td> <span class="function"><strong>V_STAT()</strong></span></td> <td> <span class="function"><a href="function.stat.html" class="function">stat()</a></span></td> </tr> <tr> <td> <span class="function"><strong>V_LSTAT()</strong></span></td> <td> <span class="function"><a href="function.lstat.html" class="function">lstat()</a></span></td> </tr> </tbody> </table> </p> </div> <div class="sect3" id="internals2.ze1.zendapi.layout.string-handling"> <h4 class="title">String Handling</h4> <p class="para"> Strings are handled a bit differently by the Zend engine than other values such as integers, Booleans, etc., which don't require additional memory allocation for storing their values. If you want to return a string from a function, introduce a new string variable to the symbol table, or do something similar, you have to make sure that the memory the string will be occupying has previously been allocated, using the aforementioned <span class="function"><strong>e*()</strong></span> functions for allocation. (This might not make much sense to you yet; just keep it somewhere in your head for now - we'll get back to it shortly.) </p> </div> <div class="sect3" id="internals2.ze1.zendapi.layout.complex-types"> <h4 class="title">Complex Types</h4> <p class="para"> Complex types such as arrays and objects require different treatment. Zend features a single API for these types - they're stored using hash tables. </p> <blockquote class="note"><p><strong class="note">Note</strong>: <p class="para"> To reduce complexity in the following source examples, we're only working with simple types such as integers at first. A discussion about creating more advanced types follows later in this chapter. </p> </p></blockquote> </div> </div> <div class="sect2" id="internals2.ze1.zendapi.build"> <h3 class="title">PHP's Automatic Build System</h3> <p class="para"> PHP 4 features an automatic build system that's very flexible. All modules reside in a subdirectory of the <var class="filename">ext</var> directory. In addition to its own sources, each module consists of a config.m4 file, for extension configuration. (for example, see <a href="http://www.gnu.org/software/m4/" class="link external">» http://www.gnu.org/software/m4/</a>) </p> <p class="para"> All these stub files are generated automatically, along with <var class="filename">.cvsignore</var>, by a little shell script named <var class="filename">ext_skel</var> that resides in the <var class="filename">ext</var> directory. As argument it takes the name of the module that you want to create. The shell script then creates a directory of the same name, along with the appropriate stub files. </p> <p class="para"> Step by step, the process looks like this: <div class="example-contents screen"> <div class="cdata"><pre> :~/cvs/php4/ext:> ./ext_skel --extname=my_module Creating directory my_module Creating basic files: config.m4 .cvsignore my_module.c php_my_module.h CREDITS EXPERIMENTAL tests/001.phpt my_module.php [done]. To use your new extension, you will have to execute the following steps: 1. $ cd .. 2. $ vi ext/my_module/config.m4 3. $ ./buildconf 4. $ ./configure --[with|enable]-my_module 5. $ make 6. $ ./php -f ext/my_module/my_module.php 7. $ vi ext/my_module/my_module.c 8. $ make Repeat steps 3-6 until you are satisfied with ext/my_module/config.m4 and step 6 confirms that your module is compiled into PHP. Then, start writing code and repeat the last two steps as often as necessary. </pre></div> </div> This instruction creates the aforementioned files. To include the new module in the automatic configuration and build process, you have to run <var class="filename">buildconf</var>, which regenerates the <var class="filename">configure</var> script by searching through the <var class="filename">ext</var> directory and including all found <var class="filename">config.m4</var> files. </p> <p class="para"> The default <var class="filename">config.m4</var> shown in <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.example.config.m4" class="xref">The default config.m4.</a> is a bit more complex: </p> <div class="example" id="internals2.ze1.zendapi.example.config.m4"> <p><strong>Example #1 The default <var class="filename">config.m4</var>.</strong></p> <div class="example-contents"> <div class="autoconfcode"><pre class="autoconfcode">dnl $Id: build.xml 297078 2010-03-29 16:25:51Z degeberg $ dnl config.m4 for extension my_module dnl Comments in this file start with the string 'dnl'. dnl Remove where necessary. This file will not work dnl without editing. dnl If your extension references something external, use with: dnl PHP_ARG_WITH(my_module, for my_module support, dnl Make sure that the comment is aligned: dnl [ --with-my_module Include my_module support]) dnl Otherwise use enable: dnl PHP_ARG_ENABLE(my_module, whether to enable my_module support, dnl Make sure that the comment is aligned: dnl [ --enable-my_module Enable my_module support]) if test "$PHP_MY_MODULE" != "no"; then dnl Write more examples of tests here... dnl # --with-my_module -> check with-path dnl SEARCH_PATH="/usr/local /usr" # you might want to change this dnl SEARCH_FOR="/include/my_module.h" # you most likely want to change this dnl if test -r $PHP_MY_MODULE/; then # path given as parameter dnl MY_MODULE_DIR=$PHP_MY_MODULE dnl else # search default path list dnl AC_MSG_CHECKING([for my_module files in default path]) dnl for i in $SEARCH_PATH ; do dnl if test -r $i/$SEARCH_FOR; then dnl MY_MODULE_DIR=$i dnl AC_MSG_RESULT(found in $i) dnl fi dnl done dnl fi dnl dnl if test -z "$MY_MODULE_DIR"; then dnl AC_MSG_RESULT([not found]) dnl AC_MSG_ERROR([Please reinstall the my_module distribution]) dnl fi dnl # --with-my_module -> add include path dnl PHP_ADD_INCLUDE($MY_MODULE_DIR/include) dnl # --with-my_module -> chech for lib and symbol presence dnl LIBNAME=my_module # you may want to change this dnl LIBSYMBOL=my_module # you most likely want to change this dnl PHP_CHECK_LIBRARY($LIBNAME,$LIBSYMBOL, dnl [ dnl PHP_ADD_LIBRARY_WITH_PATH($LIBNAME, $MY_MODULE_DIR/lib, MY_MODULE_SHARED_LIBADD) dnl AC_DEFINE(HAVE_MY_MODULELIB,1,[ ]) dnl ],[ dnl AC_MSG_ERROR([wrong my_module lib version or lib not found]) dnl ],[ dnl -L$MY_MODULE_DIR/lib -lm -ldl dnl ]) dnl dnl PHP_SUBST(MY_MODULE_SHARED_LIBADD) PHP_NEW_EXTENSION(my_module, my_module.c, $ext_shared) fi</pre> </div> </div> </div> <p class="para"> If you're unfamiliar with M4 files (now is certainly a good time to get familiar), this might be a bit confusing at first; but it's actually quite easy. </p> <p class="para"> <em class="emphasis">Note:</em> Everything prefixed with <em>dnl</em> is treated as a comment and is not parsed. </p> <p class="para"> The <var class="filename">config.m4</var> file is responsible for parsing the command-line options passed to <var class="filename">configure</var> at configuration time. This means that it has to check for required external files and do similar configuration and setup tasks. </p> <p class="para"> The default file creates two configuration directives in the <var class="filename">configure</var> script: <em>--with-my_module</em> and <em>--enable-my_module</em>. Use the first option when referring external files (such as the <em>--with-apache</em> directive that refers to the Apache directory). Use the second option when the user simply has to decide whether to enable your extension. Regardless of which option you use, you should uncomment the other, unnecessary one; that is, if you're using <em>--enable-my_module</em>, you should remove support for <em>--with-my_module</em>, and vice versa. </p> <p class="para"> By default, the <var class="filename">config.m4</var> file created by <var class="filename">ext_skel</var> accepts both directives and automatically enables your extension. Enabling the extension is done by using the <em>PHP_EXTENSION</em> macro. To change the default behavior to include your module into the PHP binary when desired by the user (by explicitly specifying <em>--enable-my_module</em> or <em>--with-my_module</em>), change the test for <em>$PHP_MY_MODULE</em> to <em>== "yes"</em>: <div class="example-contents"><div class="cdata"><pre>if test "$PHP_MY_MODULE" == "yes"; then dnl Action.. PHP_EXTENSION(my_module, $ext_shared) fi</pre></div></div> This would require you to use <em>--enable-my_module</em> each time when reconfiguring and recompiling PHP. </p> <p class="para"> <em class="emphasis">Note:</em> Be sure to run <var class="filename">buildconf</var> every time you change <var class="filename">config.m4</var>! </p> <p class="para"> We'll go into more details on the M4 macros available to your configuration scripts later in this chapter. For now, we'll simply use the default files. </p> </div> <div class="sect2" id="internals2.ze1.zendapi.creating"> <h3 class="title">Creating Extensions</h3> <p class="para"> We'll start with the creation of a very simple extension at first, which basically does nothing more than implement a function that returns the integer it receives as parameter. <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.example.simple" class="xref">A simple extension.</a> shows the source. </p> <div class="example" id="internals2.ze1.zendapi.example.simple"> <p><strong>Example #2 A simple extension.</strong></p> <div class="example-contents"> <div class="ccode"><pre class="ccode">/* include standard header */ #include "php.h" /* declaration of functions to be exported */ ZEND_FUNCTION(first_module); /* compiled function list so Zend knows what's in this module */ zend_function_entry firstmod_functions[] = { ZEND_FE(first_module, NULL) {NULL, NULL, NULL} }; /* compiled module information */ zend_module_entry firstmod_module_entry = { STANDARD_MODULE_HEADER, "First Module", firstmod_functions, NULL, NULL, NULL, NULL, NULL, NO_VERSION_YET, STANDARD_MODULE_PROPERTIES }; /* implement standard "stub" routine to introduce ourselves to Zend */ #if COMPILE_DL_FIRST_MODULE ZEND_GET_MODULE(firstmod) #endif /* implement function that is meant to be made available to PHP */ ZEND_FUNCTION(first_module) { long parameter; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &parameter) == FAILURE) { return; } RETURN_LONG(parameter); }</pre> </div> </div> </div> <p class="para"> This code contains a complete PHP module. We'll explain the source code in detail shortly, but first we'd like to discuss the build process. (This will allow the impatient to experiment before we dive into API discussions.) </p> <blockquote class="note"><p><strong class="note">Note</strong>: <p class="para"> The example source makes use of some features introduced with the Zend version used in PHP 4.1.0 and above, it won't compile with older PHP 4.0.x versions. </p> </p></blockquote> <div class="sect3" id="internals2.ze1.zendapi.creating.compiling"> <h4 class="title">Compiling Modules</h4> <p class="para"> There are basically two ways to compile modules: <ul class="itemizedlist"> <li class="listitem"> <p class="para"> Use the provided "make" mechanism in the <var class="filename">ext</var> directory, which also allows building of dynamic loadable modules. </p> </li> <li class="listitem"> <p class="para">Compile the sources manually.</p> </li> </ul> The first method should definitely be favored, since, as of PHP 4.0, this has been standardized into a sophisticated build process. The fact that it is so sophisticated is also its drawback, unfortunately - it's hard to understand at first. We'll provide a more detailed introduction to this later in the chapter, but first let's work with the default files. </p> <p class="para"> The second method is good for those who (for some reason) don't have the full PHP source tree available, don't have access to all files, or just like to juggle with their keyboard. These cases should be extremely rare, but for the sake of completeness we'll also describe this method. </p> <p class="formalpara"> <h5 class="title">Compiling Using Make</h5> <p class="para"> To compile the sample sources using the standard mechanism, copy all their subdirectories to the <var class="filename">ext</var> directory of your PHP source tree. Then run <var class="filename">buildconf</var>, which will create an updated <var class="filename">configure</var> script containing appropriate options for the new extension. By default, all the sample sources are disabled, so you don't have to fear breaking your build process. </p> </p> <p class="para"> After you run <var class="filename">buildconf</var>, <var class="filename">configure --help</var> shows the following additional modules: </p> <div class="example-contents screen"> <div class="cdata"><pre> --enable-array_experiments BOOK: Enables array experiments --enable-call_userland BOOK: Enables userland module --enable-cross_conversion BOOK: Enables cross-conversion module --enable-first_module BOOK: Enables first module --enable-infoprint BOOK: Enables infoprint module --enable-reference_test BOOK: Enables reference test module --enable-resource_test BOOK: Enables resource test module --enable-variable_creation BOOK: Enables variable-creation module </pre></div> </div> <p class="para"> The module shown earlier in <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.example.simple" class="xref">A simple extension.</a> can be enabled with <em>--enable-first_module</em> or <em>--enable-first_module=yes</em>. </p> <p class="formalpara"> <h5 class="title">Compiling Manually</h5> <p class="para"> To compile your modules manually, you need the following commands: <table class="doctable informaltable"> <col style="width: 1.00*;" /> <col style="width: 3.94*;" /> <tbody class="tbody"> <tr> <td>Action</td> <td>Command</td> </tr> <tr> <td>Compiling</td> <td>cc -fpic -DCOMPILE_DL_FIRST_MODULE=1 -I/usr/local/include -I. -I.. -I../Zend -c -o <var class="filename"><your_object_file></var> <var class="filename"><your_c_file></var></td> </tr> <tr> <td>Linking</td> <td>cc -shared -L/usr/local/lib -rdynamic -o <var class="filename"><your_module_file></var> <var class="filename"><your_object_file(s)></var></td> </tr> </tbody> </table> The command to compile the module simply instructs the compiler to generate position-independent code (<em>-fpic</em> shouldn't be omitted) and additionally defines the constant <em>COMPILE_DL_FIRST_MODULE</em> to tell the module code that it's compiled as a dynamically loadable module (the test module above checks for this; we'll discuss it shortly). After these options, it specifies a number of standard include paths that should be used as the minimal set to compile the source files. </p> </p> <p class="para"> <em class="emphasis">Note:</em> All include paths in the example are relative to the directory <var class="filename">ext</var>. If you're compiling from another directory, change the pathnames accordingly. Required items are the PHP directory, the <var class="filename">Zend</var> directory, and (if necessary), the directory in which your module resides. </p> <p class="para"> The link command is also a plain vanilla command instructing linkage as a dynamic module. </p> <p class="para"> You can include optimization options in the compilation command, although these have been omitted in this example (but some are included in the makefile template described in an earlier section). </p> <p class="para"> <em class="emphasis">Note:</em> Compiling and linking manually as a static module into the PHP binary involves very long instructions and thus is not discussed here. (It's not very efficient to type all those commands.) </p> </div> </div> <div class="sect2" id="internals2.ze1.zendapi.using"> <h3 class="title">Using Extensions</h3> <p class="para"> Depending on the build process you selected, you should either end up with a new PHP binary to be linked into your Web server (or run as CGI), or with an .so (shared object) file. If you compiled the example file <var class="filename">first_module.c</var> as a shared object, your result file should be <var class="filename">first_module.so</var>. To use it, you first have to copy it to a place from which it's accessible to PHP. For a simple test procedure, you can copy it to your <var class="filename">htdocs</var> directory and try it with the source in <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.example.testfile" class="xref">A test file for first_module.so.</a>. If you compiled it into the PHP binary, omit the call to <span class="function"><a href="function.dl.html" class="function">dl()</a></span>, as the module's functionality is instantly available to your scripts. <div class="warning"><strong class="warning">Warning</strong> <p class="para"> For security reasons, you <em class="emphasis">should not</em> put your dynamic modules into publicly accessible directories. Even though it <em class="emphasis">can</em> be done and it simplifies testing, you should put them into a separate directory in production environments. </p> </div> </p> <div class="example" id="internals2.ze1.zendapi.example.testfile"> <p><strong>Example #3 A test file for first_module.so.</strong></p> <div class="example-contents"> <div class="phpcode"><code><span style="color: #000000"> <span style="color: #0000BB"><?php<br /> <br /></span><span style="color: #FF8000">// remove next comment if necessary<br />// dl("first_module.so"); <br /><br /></span><span style="color: #0000BB">$param </span><span style="color: #007700">= </span><span style="color: #0000BB">2</span><span style="color: #007700">;<br /></span><span style="color: #0000BB">$return </span><span style="color: #007700">= </span><span style="color: #0000BB">first_module</span><span style="color: #007700">(</span><span style="color: #0000BB">$param</span><span style="color: #007700">);<br /><br />print(</span><span style="color: #DD0000">"We sent '</span><span style="color: #0000BB">$param</span><span style="color: #DD0000">' and got '</span><span style="color: #0000BB">$return</span><span style="color: #DD0000">'"</span><span style="color: #007700">);<br /><br /></span><span style="color: #0000BB">?></span> </span> </code></div> </div> </div> <p class="para"> Calling this PHP file should output the following: <div class="example-contents screen"> <div class="cdata"><pre> We sent '2' and got '2' </pre></div> </div> </p> <p class="para"> If required, the dynamic loadable module is loaded by calling the <span class="function"><a href="function.dl.html" class="function">dl()</a></span> function. This function looks for the specified shared object, loads it, and makes its functions available to PHP. The module exports the function <span class="function"><strong>first_module()</strong></span>, which accepts a single parameter, converts it to an integer, and returns the result of the conversion. </p> <p class="para"> If you've gotten this far, congratulations! You just built your first extension to PHP. </p> </div> <div class="sect2" id="internals2.ze1.zendapi.troubleshooting"> <h3 class="title">Troubleshooting</h3> <p class="para"> Actually, not much troubleshooting can be done when compiling static or dynamic modules. The only problem that could arise is that the compiler will complain about missing definitions or something similar. In this case, make sure that all header files are available and that you specified their path correctly in the compilation command. To be sure that everything is located correctly, extract a clean PHP source tree and use the automatic build in the <var class="filename">ext</var> directory with the fresh files; this will guarantee a safe compilation environment. If this fails, try manual compilation. </p> <p class="para"> PHP might also complain about missing functions in your module. (This shouldn't happen with the sample sources if you didn't modify them.) If the names of external functions you're trying to access from your module are misspelled, they'll remain as "unlinked symbols" in the symbol table. During dynamic loading and linkage by PHP, they won't resolve because of the typing errors - there are no corresponding symbols in the main binary. Look for incorrect declarations in your module file or incorrectly written external references. Note that this problem is specific to dynamic loadable modules; it doesn't occur with static modules. Errors in static modules show up at compile time. </p> </div> <div class="sect2" id="internals2.ze1.zendapi.structure"> <h3 class="title">Source Discussion</h3> <p class="para"> Now that you've got a safe build environment and you're able to include the modules into PHP files, it's time to discuss how everything works. </p> <div class="sect3" id="internals2.ze1.zendapi.structure.module"> <h4 class="title">Module Structure</h4> <p class="para"> All PHP modules follow a common structure: <ul class="itemizedlist"> <li class="listitem"> <p class="para"> Header file inclusions (to include all required macros, API definitions, etc.) </p> </li> <li class="listitem"> <p class="para"> C declaration of exported functions (required to declare the Zend function block) </p> </li> <li class="listitem"> <p class="para">Declaration of the Zend function block</p> </li> <li class="listitem"> <p class="para">Declaration of the Zend module block</p> </li> <li class="listitem"> <p class="para">Implementation of <span class="function"><strong>get_module()</strong></span></p> </li> <li class="listitem"> <p class="para">Implementation of all exported functions</p> </li> </ul></p> </div> <div class="sect3" id="internals2.ze1.zendapi.structure.headers"> <h4 class="title">Header File Inclusions</h4> <p class="para"> The only header file you really have to include for your modules is <var class="filename">php.h</var>, located in the PHP directory. This file makes all macros and API definitions required to build new modules available to your code. </p> <p class="para"> <em class="emphasis">Tip:</em> It's good practice to create a separate header file for your module that contains module-specific definitions. This header file should contain all the forward definitions for exported functions and include <var class="filename">php.h</var>. If you created your module using <em>ext_skel</em> you already have such a header file prepared. </p> </div> <div class="sect3" id="internals2.ze1.zendapi.structure.exporting-functions"> <h4 class="title">Declaring Exported Functions</h4> <p class="para"> To declare functions that are to be exported (i.e., made available to PHP as new native functions), Zend provides a set of macros. A sample declaration looks like this: <div class="example-contents"> <div class="ccode"><pre class="ccode">ZEND_FUNCTION ( my_function );</pre> </div> </div> </p> <p class="para"> <em>ZEND_FUNCTION</em> declares a new C function that complies with Zend's internal API. This means that the function is of type <em>void</em> and accepts <em>INTERNAL_FUNCTION_PARAMETERS</em> (another macro) as parameters. Additionally, it prefixes the function name with <em>zif</em>. The immediately expanded version of the above definitions would look like this: <div class="example-contents"> <div class="ccode"><pre class="ccode">void zif_my_function ( INTERNAL_FUNCTION_PARAMETERS );</pre> </div> </div> Expanding <em>INTERNAL_FUNCTION_PARAMETERS</em> results in the following: <div class="example-contents"> <div class="ccode"><pre class="ccode">void zif_my_function( int ht , zval * return_value , zval * this_ptr , int return_value_used , zend_executor_globals * executor_globals );</pre> </div> </div> </p> <p class="para"> Since the interpreter and executor core have been separated from the main PHP package, a second API defining macros and function sets has evolved: the Zend API. As the Zend API now handles quite a few of the responsibilities that previously belonged to PHP, a lot of PHP functions have been reduced to macros aliasing to calls into the Zend API. The recommended practice is to use the Zend API wherever possible, as the old API is only preserved for compatibility reasons. For example, the types <span class="envar">zval</span> and <span class="envar">pval</span> are identical. <span class="envar">zval</span> is Zend's definition; <span class="envar">pval</span> is PHP's definition (actually, <span class="envar">pval</span> is an alias for <span class="envar">zval</span> now). As the macro <em>INTERNAL_FUNCTION_PARAMETERS</em> is a Zend macro, the above declaration contains <span class="envar">zval</span>. When writing code, you should always use <span class="envar">zval</span> to conform to the new Zend API. </p> <p class="para"> The parameter list of this declaration is very important; you should keep these parameters in mind (see <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.tab.parameters" class="xref">Zend's Parameters to Functions Called from PHP</a> for descriptions). <table id="internals2.ze1.zendapi.tab.parameters" class="doctable table"> <caption><strong>Zend's Parameters to Functions Called from PHP</strong></caption> <col style="width: 1.00*;" /> <col style="width: 1.79*;" /> <tbody class="tbody"> <tr> <td>Parameter</td> <td>Description</td> </tr> <tr> <td><span class="envar">ht</span></td> <td> The number of arguments passed to the Zend function. You should not touch this directly, but instead use ZEND_NUM_ARGS() to obtain the value. </td> </tr> <tr> <td> <span class="envar">return_value</span></td> <td> This variable is used to pass any return values of your function back to PHP. Access to this variable is best done using the predefined macros. For a description of these see below. </td> </tr> <tr> <td><span class="envar">this_ptr</span></td> <td> Using this variable, you can gain access to the object in which your function is contained, if it's used within an object. Use the function <span class="function"><strong>getThis()</strong></span> to obtain this pointer. </td> </tr> <tr> <td><span class="envar">return_value_used</span></td> <td> This flag indicates whether an eventual return value from this function will actually be used by the calling script. <em>0</em> indicates that the return value is not used; <em>1</em> indicates that the caller expects a return value. Evaluation of this flag can be done to verify correct usage of the function as well as speed optimizations in case returning a value requires expensive operations (for an example, see how <var class="filename">array.c</var> makes use of this). </td> </tr> <tr> <td><span class="envar">executor_globals</span></td> <td> This variable points to global settings of the Zend engine. You'll find this useful when creating new variables, for example (more about this later). The executor globals can also be introduced to your function by using the macro <em>TSRMLS_FETCH()</em>. </td> </tr> </tbody> </table> </p> </div> <div class="sect3" id="internals2.ze1.zendapi.structure.function-block"> <h4 class="title">Declaration of the Zend Function Block</h4> <p class="para"> Now that you have declared the functions to be exported, you also have to introduce them to Zend. Introducing the list of functions is done by using an array of <span class="envar">zend_function_entry</span>. This array consecutively contains all functions that are to be made available externally, with the function's name as it should appear in PHP and its name as defined in the C source. Internally, <span class="envar">zend_function_entry</span> is defined as shown in <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.example.zend-function-entry" class="xref">Internal declaration of zend_function_entry.</a>. </p> <p class="para"> <div class="example" id="internals2.ze1.zendapi.example.zend-function-entry"> <p><strong>Example #4 Internal declaration of <span class="envar">zend_function_entry</span>.</strong></p> <div class="example-contents"> <div class="ccode"><pre class="ccode">typedef struct _zend_function_entry { char *fname; void (*handler)(INTERNAL_FUNCTION_PARAMETERS); unsigned char *func_arg_types; } zend_function_entry;</pre> </div> </div> <table class="doctable informaltable"> <col style="width: 1.00*;" /> <col style="width: 1.82*;" /> <tbody class="tbody"> <tr> <td>Entry</td> <td>Description</td> </tr> <tr> <td><span class="envar">fname</span></td> <td> Denotes the function name as seen in PHP (for example, <em>fopen</em>, <em>mysql_connect</em>, or, in our example, <em>first_module</em>). </td> </tr> <tr> <td><span class="envar">handler</span></td> <td> Pointer to the C function responsible for handling calls to this function. For example, see the standard macro <em>INTERNAL_FUNCTION_PARAMETERS</em> discussed earlier. </td> </tr> <tr> <td><span class="envar">func_arg_types</span></td> <td> Allows you to mark certain parameters so that they're forced to be passed by reference. You usually should set this to NULL. </td> </tr> </tbody> </table> </div> In the example above, the declaration looks like this: <div class="example-contents"> <div class="ccode"><pre class="ccode">zend_function_entry firstmod_functions[] = { ZEND_FE(first_module, NULL) {NULL, NULL, NULL} };</pre> </div> </div> You can see that the last entry in the list always has to be <em>{NULL, NULL, NULL}</em>. This marker has to be set for Zend to know when the end of the list of exported functions is reached. </p> <blockquote class="note"><p><strong class="note">Note</strong>: <p class="para"> You <em class="emphasis">cannot</em> use the predefined macros for the end marker, as these would try to refer to a function named "NULL"! </p> </p></blockquote> <p class="para"> The macro <em>ZEND_FE</em> (short for 'Zend Function Entry') simply expands to a structure entry in <span class="envar">zend_function_entry</span>. Note that these macros introduce a special naming scheme to your functions - your C functions will be prefixed with <em>zif_</em>, meaning that <em>ZEND_FE(first_module)</em> will refer to a C function <span class="function"><strong>zif_first_module()</strong></span>. If you want to mix macro usage with hand-coded entries (not a good practice), keep this in mind. </p> <p class="para"> Tip: Compilation errors that refer to functions named <span class="function"><strong>zif_*()</strong></span> relate to functions defined with <em>ZEND_FE</em>. </p> <p class="para"> <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.tab.funcdef-macros" class="xref">Macros for Defining Functions</a> shows a list of all the macros that you can use to define functions. </p> <table id="internals2.ze1.zendapi.tab.funcdef-macros" class="doctable table"> <caption><strong>Macros for Defining Functions</strong></caption> <col style="width: 1.00*;" /> <col style="width: 1.08*;" /> <tbody class="tbody"> <tr> <td>Macro Name</td> <td>Description</td> </tr> <tr> <td><em>ZEND_FE(name, arg_types)</em></td> <td> Defines a function entry of the name <span class="envar">name</span> in <span class="envar">zend_function_entry</span>. Requires a corresponding C function. <span class="envar">arg_types</span> needs to be set to <em>NULL</em>. This function uses automatic C function name generation by prefixing the PHP function name with <em>zif_</em>. For example, <em>ZEND_FE("first_module", NULL)</em> introduces a function <span class="function"><strong>first_module()</strong></span> to PHP and links it to the C function <span class="function"><strong>zif_first_module()</strong></span>. Use in conjunction with <em>ZEND_FUNCTION</em>. </td> </tr> <tr> <td> <em>ZEND_NAMED_FE(php_name, name, arg_types)</em> </td> <td> Defines a function that will be available to PHP by the name <span class="envar">php_name</span> and links it to the corresponding C function <span class="envar">name</span>. <span class="envar">arg_types</span> needs to be set to <em>NULL</em>. Use this function if you don't want the automatic name prefixing introduced by <em>ZEND_FE</em>. Use in conjunction with <em>ZEND_NAMED_FUNCTION</em>. </td> </tr> <tr> <td> <em>ZEND_FALIAS(name, alias, arg_types)</em> </td> <td> Defines an alias named <span class="envar">alias</span> for <span class="envar">name</span>. <span class="envar">arg_types</span> needs to be set to <em>NULL</em>. Doesn't require a corresponding C function; refers to the alias target instead. </td> </tr> <tr> <td><em>PHP_FE(name, arg_types)</em></td> <td> Old PHP API equivalent of <em>ZEND_FE</em>. </td> </tr> <tr> <td> <em>PHP_NAMED_FE(runtime_name, name, arg_types)</em> </td> <td> Old PHP API equivalent of <em>ZEND_NAMED_FE</em>. </td> </tr> </tbody> </table> <p class="para"> <em class="emphasis">Note:</em> You can't use <em>ZEND_FE</em> in conjunction with <em>PHP_FUNCTION</em>, or <em>PHP_FE</em> in conjunction with <em>ZEND_FUNCTION</em>. However, it's perfectly legal to mix <em>ZEND_FE</em> and <em>ZEND_FUNCTION</em> with <em>PHP_FE</em> and <em>PHP_FUNCTION</em> when staying with the same macro set for each function to be declared. But mixing is <em class="emphasis">not</em> recommended; instead, you're advised to use the <em>ZEND_*</em> macros only. </p> </div> <div class="sect3" id="internals2.ze1.zendapi.structure.module-block"> <h4 class="title">Declaration of the Zend Module Block</h4> <p class="para"> This block is stored in the structure <span class="envar">zend_module_entry</span> and contains all necessary information to describe the contents of this module to Zend. You can see the internal definition of this module in <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.example.zend-module-entry" class="xref">Internal declaration of zend_module_entry.</a>. </p> <div class="example" id="internals2.ze1.zendapi.example.zend-module-entry"> <p><strong>Example #5 Internal declaration of <span class="envar">zend_module_entry</span>.</strong></p> <div class="example-contents"> <div class="ccode"><pre class="ccode">typedef struct _zend_module_entry zend_module_entry; struct _zend_module_entry { unsigned short size; unsigned int zend_api; unsigned char zend_debug; unsigned char zts; char *name; zend_function_entry *functions; int (*module_startup_func)(INIT_FUNC_ARGS); int (*module_shutdown_func)(SHUTDOWN_FUNC_ARGS); int (*request_startup_func)(INIT_FUNC_ARGS); int (*request_shutdown_func)(SHUTDOWN_FUNC_ARGS); void (*info_func)(ZEND_MODULE_INFO_FUNC_ARGS); char *version; [ Rest of the structure is not interesting here ] };</pre> </div> </div> <table class="doctable informaltable"> <col style="width: 1.00*;" /> <col style="width: 1.69*;" /> <thead> <tr> <th>Entry</th> <th>Description</th> </tr> </thead> <tbody class="tbody"> <tr> <td> <span class="envar">size</span>, <span class="envar">zend_api</span>, <span class="envar">zend_debug</span> and <span class="envar">zts</span> </td> <td> Usually filled with the <em>"STANDARD_MODULE_HEADER"</em>, which fills these four members with the size of the whole zend_module_entry, the <em>ZEND_MODULE_API_NO</em>, whether it is a debug build or normal build (<em>ZEND_DEBUG</em>) and if ZTS is enabled (<em>USING_ZTS</em>). </td> </tr> <tr> <td><span class="envar">name</span></td> <td> Contains the module name (for example, <em>"File functions"</em>, <em>"Socket functions"</em>, <em>"Crypt"</em>, etc.). This name will show up in <span class="function"><a href="function.phpinfo.html" class="function">phpinfo()</a></span>, in the section "Additional Modules." </td> </tr> <tr> <td><span class="envar">functions</span></td> <td> Points to the Zend function block, discussed in the preceding section. </td> </tr> <tr> <td><span class="envar">module_startup_func</span></td> <td> This function is called once upon module initialization and can be used to do one-time initialization steps (such as initial memory allocation, etc.). To indicate a failure during initialization, return <em>FAILURE</em>; otherwise, <em>SUCCESS</em>. To mark this field as unused, use <em>NULL</em>. To declare a function, use the macro <em>ZEND_MINIT</em>. </td> </tr> <tr> <td><span class="envar">module_shutdown_func</span></td> <td> This function is called once upon module shutdown and can be used to do one-time deinitialization steps (such as memory deallocation). This is the counterpart to <span class="function"><strong>module_startup_func()</strong></span>. To indicate a failure during deinitialization, return <em>FAILURE</em>; otherwise, <em>SUCCESS</em>. To mark this field as unused, use <em>NULL</em>. To declare a function, use the macro <em>ZEND_MSHUTDOWN</em>. </td> </tr> <tr> <td><span class="envar">request_startup_func</span></td> <td> This function is called once upon every page request and can be used to do one-time initialization steps that are required to process a request. To indicate a failure here, return <em>FAILURE</em>; otherwise, <em>SUCCESS</em>. <em class="emphasis">Note:</em> As dynamic loadable modules are loaded only on page requests, the request startup function is called right after the module startup function (both initialization events happen at the same time). To mark this field as unused, use <em>NULL</em>. To declare a function, use the macro <em>ZEND_RINIT</em>. </td> </tr> <tr> <td><span class="envar">request_shutdown_func</span></td> <td> This function is called once after every page request and works as counterpart to <span class="function"><strong>request_startup_func()</strong></span>. To indicate a failure here, return <em>FAILURE</em>; otherwise, <em>SUCCESS</em>. <em class="emphasis">Note:</em> As dynamic loadable modules are loaded only on page requests, the request shutdown function is immediately followed by a call to the module shutdown handler (both deinitialization events happen at the same time). To mark this field as unused, use <em>NULL</em>. To declare a function, use the macro <em>ZEND_RSHUTDOWN</em>. </td> </tr> <tr> <td><span class="envar">info_func</span></td> <td> When <span class="function"><a href="function.phpinfo.html" class="function">phpinfo()</a></span> is called in a script, Zend cycles through all loaded modules and calls this function. Every module then has the chance to print its own "footprint" into the output page. Generally this is used to dump environmental or statistical information. To mark this field as unused, use <em>NULL</em>. To declare a function, use the macro <em>ZEND_MINFO</em>. </td> </tr> <tr> <td><span class="envar">version</span></td> <td> The version of the module. You can use <em>NO_VERSION_YET</em> if you don't want to give the module a version number yet, but we really recommend that you add a version string here. Such a version string can look like this (in chronological order): <em>"2.5-dev"</em>, <em>"2.5RC1"</em>, <em>"2.5"</em> or <em>"2.5pl3"</em>. </td> </tr> <tr> <td>Remaining structure elements</td> <td> These are used internally and can be prefilled by using the macro <em>STANDARD_MODULE_PROPERTIES_EX</em>. You should not assign any values to them. Use <em>STANDARD_MODULE_PROPERTIES_EX</em> only if you use global startup and shutdown functions; otherwise, use <em>STANDARD_MODULE_PROPERTIES</em> directly. </td> </tr> </tbody> </table> </div> <p class="para"> In our example, this structure is implemented as follows: <div class="example-contents"> <div class="ccode"><pre class="ccode">zend_module_entry firstmod_module_entry = { STANDARD_MODULE_HEADER, "First Module", firstmod_functions, NULL, NULL, NULL, NULL, NULL, NO_VERSION_YET, STANDARD_MODULE_PROPERTIES, };</pre> </div> </div> This is basically the easiest and most minimal set of values you could ever use. The module name is set to <em>First Module</em>, then the function list is referenced, after which all startup and shutdown functions are marked as being unused. </p> <p class="para"> For reference purposes, you can find a list of the macros involved in declared startup and shutdown functions in <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.tab.init-shutdown" class="xref">Macros to Declare Startup and Shutdown Functions</a>. These are not used in our basic example yet, but will be demonstrated later on. You should make use of these macros to declare your startup and shutdown functions, as these require special arguments to be passed (<em>INIT_FUNC_ARGS</em> and <em>SHUTDOWN_FUNC_ARGS</em>), which are automatically included into the function declaration when using the predefined macros. If you declare your functions manually and the PHP developers decide that a change in the argument list is necessary, you'll have to change your module sources to remain compatible. </p> <table id="internals2.ze1.zendapi.tab.init-shutdown" class="doctable table"> <caption><strong>Macros to Declare Startup and Shutdown Functions</strong></caption> <col style="width: 1.00*;" /> <col style="width: 1.41*;" /> <tbody class="tbody"> <tr> <td>Macro</td> <td>Description</td> </tr> <tr> <td><em>ZEND_MINIT(module)</em></td> <td> Declares a function for module startup. The generated name will be <em>zend_minit_<module></em> (for example, <em>zend_minit_first_module</em>). Use in conjunction with <em>ZEND_MINIT_FUNCTION</em>. </td> </tr> <tr> <td><em>ZEND_MSHUTDOWN(module)</em></td> <td> Declares a function for module shutdown. The generated name will be <em>zend_mshutdown_<module></em> (for example, <em>zend_mshutdown_first_module</em>). Use in conjunction with <em>ZEND_MSHUTDOWN_FUNCTION</em>. </td> </tr> <tr> <td><em>ZEND_RINIT(module)</em></td> <td> Declares a function for request startup. The generated name will be <em>zend_rinit_<module></em> (for example, <em>zend_rinit_first_module</em>). Use in conjunction with <em>ZEND_RINIT_FUNCTION</em>. </td> </tr> <tr> <td><em>ZEND_RSHUTDOWN(module)</em></td> <td> Declares a function for request shutdown. The generated name will be <em>zend_rshutdown_<module></em> (for example, <em>zend_rshutdown_first_module</em>). Use in conjunction with <em>ZEND_RSHUTDOWN_FUNCTION</em>. </td> </tr> <tr> <td><em>ZEND_MINFO(module)</em></td> <td> Declares a function for printing module information, used when <span class="function"><a href="function.phpinfo.html" class="function">phpinfo()</a></span> is called. The generated name will be <em>zend_info_<module></em> (for example, <em>zend_info_first_module</em>). Use in conjunction with <em>ZEND_MINFO_FUNCTION</em>. </td> </tr> </tbody> </table> </div> <div class="sect3" id="internals2.ze1.zendapi.structure.get-module"> <h4 class="title">Creation of <span class="function"><strong>get_module()</strong></span></h4> <p class="para"> This function is special to all dynamic loadable modules. Take a look at the creation via the <em>ZEND_GET_MODULE</em> macro first: </p> <div class="example-contents"> <div class="ccode"><pre class="ccode">#if COMPILE_DL_FIRSTMOD ZEND_GET_MODULE(firstmod) #endif</pre> </div> </div> <p class="para"> The function implementation is surrounded by a conditional compilation statement. This is needed since the function <span class="function"><strong>get_module()</strong></span> is only required if your module is built as a dynamic extension. By specifying a definition of <em>COMPILE_DL_FIRSTMOD</em> in the compiler command (see above for a discussion of the compilation instructions required to build a dynamic extension), you can instruct your module whether you intend to build it as a dynamic extension or as a built-in module. If you want a built-in module, the implementation of <span class="function"><strong>get_module()</strong></span> is simply left out. </p> <p class="para"> <span class="function"><strong>get_module()</strong></span> is called by Zend at load time of the module. You can think of it as being invoked by the <span class="function"><a href="function.dl.html" class="function">dl()</a></span> call in your script. Its purpose is to pass the module information block back to Zend in order to inform the engine about the module contents. </p> <p class="para"> If you don't implement a <span class="function"><strong>get_module()</strong></span> function in your dynamic loadable module, Zend will compliment you with an error message when trying to access it. </p> </div> <div class="sect3" id="internals2.ze1.zendapi.structure.implementation"> <h4 class="title">Implementation of All Exported Functions</h4> <p class="para">Implementing the exported functions is the final step. The example function in <em>first_module</em> looks like this: <div class="example-contents"> <div class="ccode"><pre class="ccode">ZEND_FUNCTION(first_module) { long parameter; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &parameter) == FAILURE) { return; } RETURN_LONG(parameter); }</pre> </div> </div> The function declaration is done using <em>ZEND_FUNCTION</em>, which corresponds to <em>ZEND_FE</em> in the function entry table (discussed earlier). </p> <p class="para"> After the declaration, code for checking and retrieving the function's arguments, argument conversion, and return value generation follows (more on this later). </p> </div> <div class="sect3" id="internals2.ze1.zendapi.structure.summary"> <h4 class="title">Summary</h4> <p class="para"> That's it, basically - there's nothing more to implementing PHP modules. Built-in modules are structured similarly to dynamic modules, so, equipped with the information presented in the previous sections, you'll be able to fight the odds when encountering PHP module source files. </p> <p class="para"> Now, in the following sections, read on about how to make use of PHP's internals to build powerful extensions. </p> </div> </div> <div class="sect2" id="internals2.ze1.zendapi.arguments"> <h3 class="title">Accepting Arguments</h3> <p class="para"> One of the most important issues for language extensions is accepting and dealing with data passed via arguments. Most extensions are built to deal with specific input data (or require parameters to perform their specific actions), and function arguments are the only real way to exchange data between the PHP level and the C level. Of course, there's also the possibility of exchanging data using predefined global values (which is also discussed later), but this should be avoided by all means, as it's extremely bad practice. </p> <p class="para"> PHP doesn't make use of any formal function declarations; this is why call syntax is always completely dynamic and never checked for errors. Checking for correct call syntax is left to the user code. For example, it's possible to call a function using only one argument at one time and four arguments the next time - both invocations are syntactically absolutely correct. </p> <div class="sect3" id="internals2.ze1.zendapi.arguments.count"> <h4 class="title">Determining the Number of Arguments</h4> <p class="para"> Since PHP doesn't have formal function definitions with support for call syntax checking, and since PHP features variable arguments, sometimes you need to find out with how many arguments your function has been called. You can use the <em>ZEND_NUM_ARGS</em> macro in this case. In previous versions of PHP, this macro retrieved the number of arguments with which the function has been called based on the function's hash table entry, <span class="envar">ht</span>, which is passed in the <em>INTERNAL_FUNCTION_PARAMETERS</em> list. As <span class="envar">ht</span> itself now contains the number of arguments that have been passed to the function, <em>ZEND_NUM_ARGS</em> has been stripped down to a dummy macro (see its definition in <var class="filename">zend_API.h</var>). But it's still good practice to use it, to remain compatible with future changes in the call interface. <em class="emphasis">Note:</em> The old PHP equivalent of this macro is <em>ARG_COUNT</em>. </p> <p class="para"> The following code checks for the correct number of arguments: <div class="example-contents"><div class="ccode"><pre class="ccode">if(ZEND_NUM_ARGS() != 2) WRONG_PARAM_COUNT;</pre> </div></div> If the function is not called with two arguments, it exits with an error message. The code snippet above makes use of the tool macro <em>WRONG_PARAM_COUNT</em>, which can be used to generate a standard error message like: <div class="cdata"><pre> "Warning: Wrong parameter count for firstmodule() in /home/www/htdocs/firstmod.php on line 5" </pre></div> </p> <p class="para"> This macro prints a default error message and then returns to the caller. Its definition can also be found in <var class="filename">zend_API.h</var> and looks like this: <div class="example-contents"> <div class="ccode"><pre class="ccode">ZEND_API void wrong_param_count(void); #define WRONG_PARAM_COUNT { wrong_param_count(); return; }</pre> </div> </div> As you can see, it calls an internal function named <span class="function"><strong>wrong_param_count()</strong></span> that's responsible for printing the warning. For details on generating customized error messages, see the later section "Printing Information." </p> </div> <div class="sect3" id="internals2.ze1.zendapi.arguments.retrieval"> <h4 class="title">Retrieving Arguments</h4> <blockquote class="note"><p><strong class="note">Note</strong>: <strong> New parameter parsing API </strong><br /> <p class="para"> This chapter documents the new Zend parameter parsing API introduced by Andrei Zmievski. It was introduced in the development stage between PHP 4.0.6 and 4.1.0. </p> </p></blockquote> <p class="para"> Parsing parameters is a very common operation and it may get a bit tedious. It would also be nice to have standardized error checking and error messages. Since PHP 4.1.0, there is a way to do just that by using the new parameter parsing API. It greatly simplifies the process of receiving parameters, but it has a drawback in that it can't be used for functions that expect variable number of parameters. But since the vast majority of functions do not fall into those categories, this parsing API is recommended as the new standard way. </p> <p class="para"> The prototype for parameter parsing function looks like this: <div class="example-contents"> <div class="ccode"><pre class="ccode">int zend_parse_parameters(int num_args TSRMLS_DC, char *type_spec, ...);</pre> </div> </div> The first argument to this function is supposed to be the number of actual parameters passed to your function, so <em>ZEND_NUM_ARGS()</em> can be used for that. The second parameter should always be <em>TSRMLS_CC</em> macro. The third argument is a string that specifies the number and types of arguments your function is expecting, similar to how printf format string specifies the number and format of the output values it should operate on. And finally the rest of the arguments are pointers to variables which should receive the values from the parameters. </p> <p class="para"> <span class="function"><strong>zend_parse_parameters()</strong></span> also performs type conversions whenever possible, so that you always receive the data in the format you asked for. Any type of scalar can be converted to another one, but conversions between complex types (arrays, objects, and resources) and scalar types are not allowed. </p> <p class="para"> If the parameters could be obtained successfully and there were no errors during type conversion, the function will return <em>SUCCESS</em>, otherwise it will return <em>FAILURE</em>. The function will output informative error messages, if the number of received parameters does not match the requested number, or if type conversion could not be performed. </p> <p class="para"> Here are some sample error messages: <div class="example-contents screen"><br /> Warning - ini_get_all() requires at most 1 parameter, 2 given<br /> Warning - wddx_deserialize() expects parameter 1 to be string, array given<br /> </div> Of course each error message is accompanied by the filename and line number on which it occurs. </p> <p class="para"> Here is the full list of type specifiers: <ul class="itemizedlist"> <li class="listitem"> <p class="para"><em>l</em> - long</p> </li> <li class="listitem"> <p class="para"><em>d</em> - double</p> </li> <li class="listitem"> <p class="para"><em>s</em> - string (with possible null bytes) and its length</p> </li> <li class="listitem"> <p class="para"><em>b</em> - boolean</p> </li> <li class="listitem"> <p class="para"><em>r</em> - resource, stored in <em>zval*</em></p> </li> <li class="listitem"> <p class="para"><em>a</em> - array, stored in <em>zval*</em></p> </li> <li class="listitem"> <p class="para"><em>o</em> - object (of any class), stored in <em>zval*</em></p> </li> <li class="listitem"> <p class="para"><em>O</em> - object (of class specified by class entry), stored in <em>zval*</em></p> </li> <li class="listitem"> <p class="para"><em>z</em> - the actual <em>zval*</em></p> </li> </ul> The following characters also have a meaning in the specifier string: <ul class="itemizedlist"> <li class="listitem"> <p class="para"> <em>|</em> - indicates that the remaining parameters are optional. The storage variables corresponding to these parameters should be initialized to default values by the extension, since they will not be touched by the parsing function if the parameters are not passed. </p> </li> <li class="listitem"> <p class="para"> <em>/</em> - the parsing function will call <span class="function"><strong>SEPARATE_ZVAL_IF_NOT_REF()</strong></span> on the parameter it follows, to provide a copy of the parameter, unless it's a reference. </p> </li> <li class="listitem"> <p class="para"> <em>!</em> - the parameter it follows can be of specified type or <em>NULL</em> (only applies to a, o, O, r, and z). If <em>NULL</em> value is passed by the user, the storage pointer will be set to <em>NULL</em>. </p> </li> </ul> </p> <p class="para"> The best way to illustrate the usage of this function is through examples: <div class="example-contents"> <div class="ccode"><pre class="ccode">/* Gets a long, a string and its length, and a zval. */ long l; char *s; int s_len; zval *param; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lsz", &l, &s, &s_len, &param) == FAILURE) { return; } /* Gets an object of class specified by my_ce, and an optional double. */ zval *obj; double d = 0.5; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|d", &obj, my_ce, &d) == FAILURE) { return; } /* Gets an object or null, and an array. If null is passed for object, obj will be set to NULL. */ zval *obj; zval *arr; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O!a", &obj, &arr) == FAILURE) { return; } /* Gets a separated array. */ zval *arr; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a/", &arr) == FAILURE) { return; } /* Get only the first three parameters (useful for varargs functions). */ zval *z; zend_bool b; zval *r; if (zend_parse_parameters(3, "zbr!", &z, &b, &r) == FAILURE) { return; }</pre> </div> </div> </p> <p class="para"> Note that in the last example we pass 3 for the number of received parameters, instead of <span class="function"><strong>ZEND_NUM_ARGS()</strong></span>. What this lets us do is receive the least number of parameters if our function expects a variable number of them. Of course, if you want to operate on the rest of the parameters, you will have to use <span class="function"><strong>zend_get_parameters_array_ex()</strong></span> to obtain them. </p> <p class="para"> The parsing function has an extended version that allows for an additional flags argument that controls its actions. <div class="example-contents"> <div class="ccode"><pre class="ccode">int zend_parse_parameters_ex(int flags, int num_args TSRMLS_DC, char *type_spec, ...);</pre> </div> </div> </p> <p class="para"> The only flag you can pass currently is <em>ZEND_PARSE_PARAMS_QUIET</em>, which instructs the function to not output any error messages during its operation. This is useful for functions that expect several sets of completely different arguments, but you will have to output your own error messages. </p> <p class="para"> For example, here is how you would get either a set of three longs or a string: <div class="example-contents"> <div class="ccode"><pre class="ccode">long l1, l2, l3; char *s; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "lll", &l1, &l2, &l3) == SUCCESS) { /* manipulate longs */ } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "s", &s, &s_len) == SUCCESS) { /* manipulate string */ } else { php_error(E_WARNING, "%s() takes either three long values or a string as argument", get_active_function_name(TSRMLS_C)); return; }</pre> </div> </div> </p> <p class="para"> With all the abovementioned ways of receiving function parameters you should have a good handle on this process. For even more example, look through the source code for extensions that are shipped with PHP - they illustrate every conceivable situation. </p> </div> <div class="sect3" id="internals2.ze1.zendapi.arguments.deprecated-retrieval"> <h4 class="title">Old way of retrieving arguments (deprecated)</h4> <blockquote class="note"><p><strong class="note">Note</strong>: <strong> Deprecated parameter parsing API </strong><br /> <p class="para"> This API is deprecated and superseded by the new ZEND parameter parsing API. </p> </p></blockquote> <p class="para"> After having checked the number of arguments, you need to get access to the arguments themselves. This is done with the help of <span class="function"><strong>zend_get_parameters_ex()</strong></span>: <div class="example-contents"> <div class="ccode"><pre class="ccode">zval **parameter; if(zend_get_parameters_ex(1, &parameter) != SUCCESS) WRONG_PARAM_COUNT;</pre> </div> </div> All arguments are stored in a <span class="envar">zval</span> container, which needs to be pointed to <em class="emphasis">twice</em>. The snippet above tries to retrieve one argument and make it available to us via the <span class="envar">parameter</span> pointer. </p> <p class="para"> <span class="function"><strong>zend_get_parameters_ex()</strong></span> accepts at least two arguments. The first argument is the number of arguments to retrieve (which should match the number of arguments with which the function has been called; this is why it's important to check for correct call syntax). The second argument (and all following arguments) are pointers to pointers to pointers to <span class="envar">zval</span>s. (Confusing, isn't it?) All these pointers are required because Zend works internally with <span class="envar">**zval</span>; to adjust a local <span class="envar">**zval</span> in our function, <span class="function"><strong>zend_get_parameters_ex()</strong></span> requires a pointer to it. </p> <p class="para"> The return value of <span class="function"><strong>zend_get_parameters_ex()</strong></span> can either be <em>SUCCESS</em> or <em>FAILURE</em>, indicating (unsurprisingly) success or failure of the argument processing. A failure is most likely related to an incorrect number of arguments being specified, in which case you should exit with <em>WRONG_PARAM_COUNT</em>. </p> <p class="para"> To retrieve more than one argument, you can use a similar snippet: <div class="example-contents"> <div class="ccode"><pre class="ccode">zval **param1, **param2, **param3, **param4; if(zend_get_parameters_ex(4, &param1, &param2, &param3, &param4) != SUCCESS) WRONG_PARAM_COUNT;</pre> </div> </div> </p> <p class="para"> <span class="function"><strong>zend_get_parameters_ex()</strong></span> only checks whether you're trying to retrieve too many parameters. If the function is called with five arguments, but you're only retrieving three of them with <span class="function"><strong>zend_get_parameters_ex()</strong></span>, you won't get an error but will get the first three parameters instead. Subsequent calls of <span class="function"><strong>zend_get_parameters_ex()</strong></span> won't retrieve the remaining arguments, but will get the same arguments again. </p> </div> <div class="sect3" id="internals2.ze1.zendapi.arguments.variable"> <h4 class="title">Dealing with a Variable Number of Arguments/Optional Parameters</h4> <p class="para"> If your function is meant to accept a variable number of arguments, the snippets just described are sometimes suboptimal solutions. You have to create a line calling <span class="function"><strong>zend_get_parameters_ex()</strong></span> for every possible number of arguments, which is often unsatisfying. </p> <p class="para"> For this case, you can use the function <span class="function"><strong>zend_get_parameters_array_ex()</strong></span>, which accepts the number of parameters to retrieve and an array in which to store them: <div class="example-contents"> <div class="ccode"><pre class="ccode">zval **parameter_array[4]; /* get the number of arguments */ argument_count = ZEND_NUM_ARGS(); /* see if it satisfies our minimal request (2 arguments) */ /* and our maximal acceptance (4 arguments) */ if(argument_count < 2 || argument_count > 4) WRONG_PARAM_COUNT; /* argument count is correct, now retrieve arguments */ if(zend_get_parameters_array_ex(argument_count, parameter_array) != SUCCESS) WRONG_PARAM_COUNT;</pre> </div> </div> First, the number of arguments is checked to make sure that it's in the accepted range. After that, <span class="function"><strong>zend_get_parameters_array_ex()</strong></span> is used to fill <span class="envar">parameter_array</span> with valid pointers to the argument values. </p> <p class="para"> A very clever implementation of this can be found in the code handling PHP's <span class="function"><a href="function.fsockopen.html" class="function">fsockopen()</a></span> located in <var class="filename">ext/standard/fsock.c</var>, as shown in <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.example.fsockopen" class="xref">PHP's implementation of variable arguments in fsockopen().</a>. Don't worry if you don't know all the functions used in this source yet; we'll get to them shortly. </p> <div class="example" id="internals2.ze1.zendapi.example.fsockopen"> <p><strong>Example #6 PHP's implementation of variable arguments in fsockopen().</strong></p> <div class="example-contents"> <div class="ccode"><pre class="ccode">pval **args[5]; int *sock=emalloc(sizeof(int)); int *sockp; int arg_count=ARG_COUNT(ht); int socketd = -1; unsigned char udp = 0; struct timeval timeout = { 60, 0 }; unsigned short portno; unsigned long conv; char *key = NULL; FLS_FETCH(); if (arg_count > 5 || arg_count < 2 || zend_get_parameters_array_ex(arg_count,args)==FAILURE) { CLOSE_SOCK(1); WRONG_PARAM_COUNT; } switch(arg_count) { case 5: convert_to_double_ex(args[4]); conv = (unsigned long) (Z_DVAL_PP(args[4]) * 1000000.0); timeout.tv_sec = conv / 1000000; timeout.tv_usec = conv % 1000000; /* fall-through */ case 4: if (!PZVAL_IS_REF(*args[3])) { php_error(E_WARNING,"error string argument to fsockopen not passed by reference"); } pval_copy_constructor(*args[3]); ZVAL_EMPTY_STRING(*args[3]); /* fall-through */ case 3: if (!PZVAL_IS_REF(*args[2])) { php_error(E_WARNING,"error argument to fsockopen not passed by reference"); return; } ZVAL_LONG(*args[2], 0); break; } convert_to_string_ex(args[0]); convert_to_long_ex(args[1]); portno = (unsigned short) Z_LVAL_P(args[1]); key = emalloc(Z_STRLEN_P(args[0]) + 10);</pre> </div> </div> </div> <p class="para"> <span class="function"><a href="function.fsockopen.html" class="function">fsockopen()</a></span> accepts two, three, four, or five parameters. After the obligatory variable declarations, the function checks for the correct range of arguments. Then it uses a fall-through mechanism in a <em>switch()</em> statement to deal with all arguments. The <em>switch()</em> statement starts with the maximum number of arguments being passed (five). After that, it automatically processes the case of four arguments being passed, then three, by omitting the otherwise obligatory <em>break</em> keyword in all stages. After having processed the last case, it exits the <em>switch()</em> statement and does the minimal argument processing needed if the function is invoked with only two arguments. </p> <p class="para"> This multiple-stage type of processing, similar to a stairway, allows convenient processing of a variable number of arguments. </p> </div> <div class="sect3" id="zend.arguments.access"> <h4 class="title">Accessing Arguments</h4> <p class="para"> To access arguments, it's necessary for each argument to have a clearly defined type. Again, PHP's extremely dynamic nature introduces some quirks. Because PHP never does any kind of type checking, it's possible for a caller to pass any kind of data to your functions, whether you want it or not. If you expect an integer, for example, the caller might pass an array, and vice versa - PHP simply won't notice. </p> <p class="para"> To work around this, you have to use a set of API functions to force a type conversion on every argument that's being passed (see <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.tab.arg-conv" class="xref">Argument Conversion Functions</a>). </p> <p class="para"> <em class="emphasis">Note:</em> All conversion functions expect a <span class="envar">**zval</span> as parameter. </p> <table id="internals2.ze1.zendapi.tab.arg-conv" class="doctable table"> <caption><strong>Argument Conversion Functions</strong></caption> <col style="width: 1.02*;" /> <col style="width: 1.00*;" /> <tbody class="tbody"> <tr> <td>Function</td> <td>Description</td> </tr> <tr> <td> <span class="function"><strong>convert_to_boolean_ex()</strong></span></td> <td> Forces conversion to a Boolean type. Boolean values remain untouched. Longs, doubles, and strings containing <em>0</em> as well as NULL values will result in Boolean <em>0</em> (FALSE). Arrays and objects are converted based on the number of entries or properties, respectively, that they have. Empty arrays and objects are converted to FALSE; otherwise, to TRUE. All other values result in a Boolean <em>1</em> (TRUE). </td> </tr> <tr> <td> <span class="function"><strong>convert_to_long_ex()</strong></span></td> <td> Forces conversion to a long, the default integer type. NULL values, Booleans, resources, and of course longs remain untouched. Doubles are truncated. Strings containing an integer are converted to their corresponding numeric representation, otherwise resulting in <em>0</em>. Arrays and objects are converted to <em>0</em> if empty, <em>1</em> otherwise. </td> </tr> <tr> <td> <span class="function"><strong>convert_to_double_ex()</strong></span></td> <td> Forces conversion to a double, the default floating-point type. NULL values, Booleans, resources, longs, and of course doubles remain untouched. Strings containing a number are converted to their corresponding numeric representation, otherwise resulting in <em>0.0</em>. Arrays and objects are converted to <em>0.0</em> if empty, <em>1.0</em> otherwise. </td> </tr> <tr> <td> <span class="function"><strong>convert_to_string_ex()</strong></span></td> <td> Forces conversion to a string. Strings remain untouched. NULL values are converted to an empty string. Booleans containing TRUE are converted to <em>"1"</em>, otherwise resulting in an empty string. Longs and doubles are converted to their corresponding string representation. Arrays are converted to the string <em>"Array"</em> and objects to the string <em>"Object"</em>. </td> </tr> <tr> <td><em>convert_to_array_ex(value)</em></td> <td> Forces conversion to an array. Arrays remain untouched. Objects are converted to an array by assigning all their properties to the array table. All property names are used as keys, property contents as values. NULL values are converted to an empty array. All other values are converted to an array that contains the specific source value in the element with the key <em>0</em>. </td> </tr> <tr> <td><em>convert_to_object_ex(value)</em></td> <td> Forces conversion to an object. Objects remain untouched. NULL values are converted to an empty object. Arrays are converted to objects by introducing their keys as properties into the objects and their values as corresponding property contents in the object. All other types result in an object with the property <em>scalar</em> , having the corresponding source value as content. </td> </tr> <tr> <td><em>convert_to_null_ex(value)</em></td> <td>Forces the type to become a NULL value, meaning empty.</td> </tr> </tbody> </table> <blockquote class="note"><p><strong class="note">Note</strong>: <p class="para"> You can find a demonstration of the behavior in <var class="filename">cross_conversion.php</var> on the accompanying CD-ROM. </p> </p></blockquote> <div class="mediaobject"> <div class="imageobject"> <img src="images/befd863081615f539082d9ff76bf7b39-zend.04-cross-converter.png" alt="Cross-conversion behavior of PHP." width="609" height="523" /> </div> </div> <p class="para"> Using these functions on your arguments will ensure type safety for all data that's passed to you. If the supplied type doesn't match the required type, PHP forces dummy contents on the resulting value (empty strings, arrays, or objects, <em>0</em> for numeric values, <em>FALSE</em> for Booleans) to ensure a defined state. </p> <p class="para"> Following is a quote from the sample module discussed previously, which makes use of the conversion functions: <div class="example-contents"> <div class="ccode"><pre class="ccode">zval **parameter; if((ZEND_NUM_ARGS() != 1) || (zend_get_parameters_ex(1, &parameter) != SUCCESS)) { WRONG_PARAM_COUNT; } convert_to_long_ex(parameter); RETURN_LONG(Z_LVAL_P(parameter));</pre> </div> </div> After retrieving the parameter pointer, the parameter value is converted to a long (an integer), which also forms the return value of this function. Understanding access to the contents of the value requires a short discussion of the <span class="envar">zval</span> type, whose definition is shown in <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.example.zval-typedef" class="xref">PHP/Zend zval type definition.</a>. </p> <div class="example" id="internals2.ze1.zendapi.example.zval-typedef"> <p><strong>Example #7 PHP/Zend <span class="envar">zval</span> type definition.</strong></p> <div class="example-contents"> <div class="ccode"><pre class="ccode">typedef pval zval; typedef struct _zval_struct zval; typedef union _zvalue_value { long lval; /* long value */ double dval; /* double value */ struct { char *val; int len; } str; HashTable *ht; /* hash table value */ struct { zend_class_entry *ce; HashTable *properties; } obj; } zvalue_value; struct _zval_struct { /* Variable information */ zvalue_value value; /* value */ unsigned char type; /* active type */ unsigned char is_ref; short refcount; };</pre> </div> </div> </div> <p class="para"> Actually, <span class="envar">pval</span> (defined in <var class="filename">php.h</var>) is only an alias of <span class="envar">zval</span> (defined in <var class="filename">zend.h</var>), which in turn refers to <span class="envar">_zval_struct</span>. This is a most interesting structure. <span class="envar">_zval_struct</span> is the "master" structure, containing the value structure, type, and reference information. The substructure <span class="envar">zvalue_value</span> is a union that contains the variable's contents. Depending on the variable's type, you'll have to access different members of this union. For a description of both structures, see <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.tab.struct-zval" class="xref">Zend zval Structure</a>, <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.tab.struct-zvalue-value" class="xref">Zend zvalue_value Structure</a> and <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.tab.ztype-constants" class="xref">Zend Variable Type Constants</a>. </p> <table id="internals2.ze1.zendapi.tab.struct-zval" class="doctable table"> <caption><strong>Zend <span class="envar">zval</span> Structure</strong></caption> <col style="width: 1.00*;" /> <col style="width: 1.66*;" /> <tbody class="tbody"> <tr> <td>Entry</td> <td>Description</td> </tr> <tr> <td><span class="envar">value</span></td> <td> Union containing this variable's contents. See <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.tab.struct-zvalue-value" class="xref">Zend zvalue_value Structure</a> for a description. </td> </tr> <tr> <td><span class="envar">type</span></td> <td> Contains this variable's type. For a list of available types, see <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.tab.ztype-constants" class="xref">Zend Variable Type Constants</a>. </td> </tr> <tr> <td><span class="envar">is_ref</span></td> <td> 0 means that this variable is not a reference; 1 means that this variable is a reference to another variable. </td> </tr> <tr> <td><span class="envar">refcount</span></td> <td> The number of references that exist for this variable. For every new reference to the value stored in this variable, this counter is increased by 1. For every lost reference, this counter is decreased by 1. When the reference counter reaches 0, no references exist to this value anymore, which causes automatic freeing of the value. </td> </tr> </tbody> </table> <table id="internals2.ze1.zendapi.tab.struct-zvalue-value" class="doctable table"> <caption><strong>Zend <span class="envar">zvalue_value</span> Structure</strong></caption> <col style="width: 1.00*;" /> <col style="width: 1.66*;" /> <tbody class="tbody"> <tr> <td>Entry</td> <td>Description</td> </tr> <tr> <td><span class="envar">lval</span></td> <td>Use this property if the variable is of the type <em>IS_LONG</em>, <em>IS_BOOLEAN</em>, or <em>IS_RESOURCE</em>.</td> </tr> <tr> <td><span class="envar">dval</span></td> <td>Use this property if the variable is of the type <em>IS_DOUBLE</em>.</td> </tr> <tr> <td><span class="envar">str</span></td> <td> This structure can be used to access variables of the type <em>IS_STRING</em>. The member <span class="envar">len</span> contains the string length; the member <span class="envar">val</span> points to the string itself. Zend uses C strings; thus, the string length contains a trailing <em>0x00</em>.</td> </tr> <tr> <td><span class="envar">ht</span></td> <td>This entry points to the variable's hash table entry if the variable is an array.</td> </tr> <tr> <td><span class="envar">obj</span></td> <td>Use this property if the variable is of the type <em>IS_OBJECT</em>.</td> </tr> </tbody> </table> <table id="internals2.ze1.zendapi.tab.ztype-constants" class="doctable table"> <caption><strong>Zend Variable Type Constants</strong></caption> <col style="width: 1.00*;" /> <col style="width: 1.65*;" /> <tbody class="tbody"> <tr> <td>Constant</td> <td>Description</td> </tr> <tr> <td><em>IS_NULL</em></td> <td>Denotes a NULL (empty) value.</td> </tr> <tr> <td><em>IS_LONG</em></td> <td>A long (integer) value.</td> </tr> <tr> <td><em>IS_DOUBLE</em></td> <td>A double (floating point) value.</td> </tr> <tr> <td><em>IS_STRING</em></td> <td>A string.</td> </tr> <tr> <td><em>IS_ARRAY</em></td> <td>Denotes an array.</td> </tr> <tr> <td><em>IS_OBJECT</em></td> <td>An object.</td> </tr> <tr> <td><em>IS_BOOL</em></td> <td>A Boolean value.</td> </tr> <tr> <td><em>IS_RESOURCE</em></td> <td>A resource (for a discussion of resources, see the appropriate section below).</td> </tr> <tr> <td><em>IS_CONSTANT</em></td> <td>A constant (defined) value.</td> </tr> </tbody> </table> <p class="para"> To access a long you access <span class="envar">zval.value.lval</span>, to access a double you use <span class="envar">zval.value.dval</span>, and so on. Because all values are stored in a union, trying to access data with incorrect union members results in meaningless output. </p> <p class="para"> Accessing arrays and objects is a bit more complicated and is discussed later. </p> </div> <div class="sect3" id="internals2.ze1.zendapi.arguments.by-reference"> <h4 class="title">Dealing with Arguments Passed by Reference</h4> <p class="para"> If your function accepts arguments passed by reference that you intend to modify, you need to take some precautions. </p> <p class="para"> What we didn't say yet is that under the circumstances presented so far, you don't have write access to any <span class="envar">zval</span> containers designating function parameters that have been passed to you. Of course, you can change any <span class="envar">zval</span> containers that you created within your function, but you mustn't change any <span class="envar">zval</span>s that refer to Zend-internal data! </p> <p class="para"> We've only discussed the so-called <span class="function"><strong>*_ex()</strong></span> API so far. You may have noticed that the API functions we've used are called <span class="function"><strong>zend_get_parameters_ex()</strong></span> instead of <span class="function"><strong>zend_get_parameters()</strong></span>, <span class="function"><strong>convert_to_long_ex()</strong></span> instead of <span class="function"><strong>convert_to_long()</strong></span>, etc. The <span class="function"><strong>*_ex()</strong></span> functions form the so-called new "extended" Zend API. They give a minor speed increase over the old API, but as a tradeoff are only meant for providing read-only access. </p> <p class="para"> Because Zend works internally with references, different variables may reference the same value. Write access to a <span class="envar">zval</span> container requires this container to contain an isolated value, meaning a value that's not referenced by any other containers. If a <span class="envar">zval</span> container were referenced by other containers and you changed the referenced <span class="envar">zval</span>, you would automatically change the contents of the other containers referencing this <span class="envar">zval</span> (because they'd simply point to the changed value and thus change their own value as well). </p> <p class="para"> <span class="function"><strong>zend_get_parameters_ex()</strong></span> doesn't care about this situation, but simply returns a pointer to the desired <span class="envar">zval</span> containers, whether they consist of references or not. Its corresponding function in the traditional API, <span class="function"><strong>zend_get_parameters()</strong></span>, immediately checks for referenced values. If it finds a reference, it creates a new, isolated <span class="envar">zval</span> container; copies the referenced data into this newly allocated space; and then returns a pointer to the new, isolated value. </p> <p class="para"> This action is called <em class="emphasis">zval separation</em> (or pval separation). Because the <span class="function"><strong>*_ex()</strong></span> API doesn't perform zval separation, it's considerably faster, while at the same time disabling write access. </p> <p class="para"> To change parameters, however, write access is required. Zend deals with this situation in a special way: Whenever a parameter to a function is passed by reference, it performs automatic zval separation. This means that whenever you're calling a function like this in PHP, Zend will automatically ensure that <span class="envar">$parameter</span> is being passed as an isolated value, rendering it to a write-safe state: <div class="example-contents"> <div class="ccode"><pre class="ccode">my_function(&$parameter);</pre> </div> </div> </p> <p class="para"> But this <em class="emphasis">is not</em> the case with regular parameters! All other parameters that are not passed by reference are in a read-only state. </p> <p class="para"> This requires you to make sure that you're really working with a reference - otherwise you might produce unwanted results. To check for a parameter being passed by reference, you can use the macro <em>PZVAL_IS_REF</em>. This macro accepts a <em>zval*</em> to check if it is a reference or not. Examples are given in in <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.example.pass-by-ref" class="xref">Testing for referenced parameter passing.</a>. </p> <div class="example" id="internals2.ze1.zendapi.example.pass-by-ref"> <p><strong>Example #8 Testing for referenced parameter passing.</strong></p> <div class="example-contents"> <div class="ccode"><pre class="ccode">zval *parameter; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &parameter) == FAILURE) return; /* check for parameter being passed by reference */ if (!PZVAL_IS_REF(parameter)) { { zend_error(E_WARNING, "Parameter wasn't passed by reference"); RETURN_NULL(); } /* make changes to the parameter */ ZVAL_LONG(parameter, 10);</pre> </div> </div> <div class="mediaobject"> <div class="imageobject"> <img src="images/befd863081615f539082d9ff76bf7b39-zend.05-reference-test.png" alt="Testing for referenced parameter passing" width="609" height="629" /> </div> </div> </div> </div> <div class="sect3" id="internals2.ze1.zendapi.arguments.write-safety"> <h4 class="title">Assuring Write Safety for Other Parameters</h4> <p class="para"> You might run into a situation in which you need write access to a parameter that's retrieved with <span class="function"><strong>zend_get_parameters_ex()</strong></span> but not passed by reference. For this case, you can use the macro <em>SEPARATE_ZVAL</em>, which does a zval separation on the provided container. The newly generated <span class="envar">zval</span> is detached from internal data and has only a local scope, meaning that it can be changed or destroyed without implying global changes in the script context: <div class="example-contents"> <div class="ccode"><pre class="ccode">zval **parameter; /* retrieve parameter */ zend_get_parameters_ex(1, &parameter); /* at this stage, <parameter> still is connected */ /* to Zend's internal data buffers */ /* make <parameter> write-safe */ SEPARATE_ZVAL(parameter); /* now we can safely modify <parameter> */ /* without implying global changes */</pre> </div> </div> <em>SEPARATE_ZVAL</em> uses <span class="function"><strong>emalloc()</strong></span> to allocate the new <span class="envar">zval</span> container, which means that even if you don't deallocate this memory yourself, it will be destroyed automatically upon script termination. However, doing a lot of calls to this macro without freeing the resulting containers will clutter up your RAM. </p> <p class="para"> <em class="emphasis">Note:</em> As you can easily work around the lack of write access in the "traditional" API (with <span class="function"><strong>zend_get_parameters()</strong></span> and so on), this API seems to be obsolete, and is not discussed further in this chapter. </p> </div> </div> <div class="sect2" id="internals2.ze1.zendapi.variables"> <h3 class="title">Creating Variables</h3> <p class="para"> When exchanging data from your own extensions with PHP scripts, one of the most important issues is the creation of variables. This section shows you how to deal with the variable types that PHP supports. </p> <div class="sect3" id="internals2.ze1.zendapi.variables.overview"> <h4 class="title">Overview</h4> <p class="para"> To create new variables that can be seen "from the outside" by the executing script, you need to allocate a new <span class="envar">zval</span> container, fill this container with meaningful values, and then introduce it to Zend's internal symbol table. This basic process is common to all variable creations: </p> <div class="example-contents"> <div class="ccode"><pre class="ccode">zval *new_variable; /* allocate and initialize new container */ MAKE_STD_ZVAL(new_variable); /* set type and variable contents here, see the following sections */ /* introduce this variable by the name "new_variable_name" into the symbol table */ ZEND_SET_SYMBOL(EG(active_symbol_table), "new_variable_name", new_variable); /* the variable is now accessible to the script by using $new_variable_name */</pre> </div> </div> <p class="para"> The macro <em>MAKE_STD_ZVAL</em> allocates a new <span class="envar">zval</span> container using <em>ALLOC_ZVAL</em> and initializes it using <em>INIT_ZVAL</em>. As implemented in Zend at the time of this writing, <em class="emphasis">initializing</em> means setting the reference count to <em>1</em> and clearing the <span class="envar">is_ref</span> flag, but this process could be extended later - this is why it's a good idea to keep using <em>MAKE_STD_ZVAL</em> instead of only using <em>ALLOC_ZVAL</em>. If you want to optimize for speed (and you don't have to explicitly initialize the <span class="envar">zval</span> container here), you can use <em>ALLOC_ZVAL</em>, but this isn't recommended because it doesn't ensure data integrity. </p> <p class="para"> <em>ZEND_SET_SYMBOL</em> takes care of introducing the new variable to Zend's symbol table. This macro checks whether the value already exists in the symbol table and converts the new symbol to a reference if so (with automatic deallocation of the old <span class="envar">zval</span> container). This is the preferred method if speed is not a crucial issue and you'd like to keep memory usage low. </p> <p class="para"> Note that <em>ZEND_SET_SYMBOL</em> makes use of the Zend executor globals via the macro <em>EG</em>. By specifying <em>EG(active_symbol_table)</em>, you get access to the currently active symbol table, dealing with the active, local scope. The local scope may differ depending on whether the function was invoked from within a function. </p> <p class="para"> If you need to optimize for speed and don't care about optimal memory usage, you can omit the check for an existing variable with the same value and instead force insertion into the symbol table by using <span class="function"><strong>zend_hash_update()</strong></span>: <div class="example-contents"> <div class="ccode"><pre class="ccode">zval *new_variable; /* allocate and initialize new container */ MAKE_STD_ZVAL(new_variable); /* set type and variable contents here, see the following sections */ /* introduce this variable by the name "new_variable_name" into the symbol table */ zend_hash_update( EG(active_symbol_table), "new_variable_name", strlen("new_variable_name") + 1, &new_variable, sizeof(zval *), NULL );</pre> </div> </div> This is actually the standard method used in most modules. </p> <p class="para"> The variables generated with the snippet above will always be of local scope, so they reside in the context in which the function has been called. To create new variables in the global scope, use the same method but refer to another symbol table: <div class="example-contents"> <div class="ccode"><pre class="ccode">zval *new_variable; // allocate and initialize new container MAKE_STD_ZVAL(new_variable); // // set type and variable contents here // // introduce this variable by the name "new_variable_name" into the global symbol table ZEND_SET_SYMBOL(&EG(symbol_table), "new_variable_name", new_variable);</pre> </div> </div> The macro <em>ZEND_SET_SYMBOL</em> is now being called with a reference to the main, global symbol table by referring <em>EG(symbol_table)</em>. </p> <p class="para"> <em class="emphasis">Note:</em> The <span class="envar">active_symbol_table</span> variable is a pointer, but <span class="envar">symbol_table</span> is not. This is why you have to use <em>EG(active_symbol_table)</em> and <em>&EG(symbol_table)</em> as parameters to <em>ZEND_SET_SYMBOL</em> - it requires a pointer. </p> <p class="para"> Similarly, to get a more efficient version, you can hardcode the symbol table update: <div class="example-contents"> <div class="ccode"><pre class="ccode">zval *new_variable; // allocate and initialize new container MAKE_STD_ZVAL(new_variable); // // set type and variable contents here // // introduce this variable by the name "new_variable_name" into the global symbol table zend_hash_update( &EG(symbol_table), "new_variable_name", strlen("new_variable_name") + 1, &new_variable, sizeof(zval *), NULL );</pre> </div> </div> <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.example.variable-scopes" class="xref">Creating variables with different scopes.</a> shows a sample source that creates two variables - <span class="envar">local_variable</span> with a local scope and <span class="envar">global_variable</span> with a global scope (see Figure 9.7). The full example can be found on the CD-ROM. </p> <p class="para"> Note: You can see that the global variable is actually not accessible from within the function. This is because it's not imported into the local scope using <em>global $global_variable;</em> in the PHP source. </p> <div class="example" id="internals2.ze1.zendapi.example.variable-scopes"> <p><strong>Example #9 Creating variables with different scopes.</strong></p> <div class="example-contents"> <div class="ccode"><pre class="ccode">ZEND_FUNCTION(variable_creation) { zval *new_var1, *new_var2; MAKE_STD_ZVAL(new_var1); MAKE_STD_ZVAL(new_var2); ZVAL_LONG(new_var1, 10); ZVAL_LONG(new_var2, 5); ZEND_SET_SYMBOL(EG(active_symbol_table), "local_variable", new_var1); ZEND_SET_SYMBOL(&EG(symbol_table), "global_variable", new_var2); RETURN_NULL(); }</pre> </div> </div> <div class="mediaobject"> <div class="imageobject"> <img src="images/befd863081615f539082d9ff76bf7b39-zend.06-variable-creation.png" alt="Creating variables with different scopes" width="609" height="629" /> </div> </div> </div> </div> <div class="sect3" id="internals2.ze1.zendapi.variables.long"> <h4 class="title">Longs (Integers)</h4> <p class="para">Now let's get to the assignment of data to variables, starting with longs. Longs are PHP's integers and are very simple to store. Looking at the <span class="envar">zval.value</span> container structure discussed earlier in this chapter, you can see that the long data type is directly contained in the union, namely in the <span class="envar">lval</span> field. The corresponding <span class="envar">type</span> value for longs is <em>IS_LONG</em> (see <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.example.create-long" class="xref">Creation of a long.</a>). <div class="example" id="internals2.ze1.zendapi.example.create-long"> <p><strong>Example #10 Creation of a long.</strong></p> <div class="example-contents"> <div class="ccode"><pre class="ccode">zval *new_long; MAKE_STD_ZVAL(new_long); new_long-&gt;type = IS_LONG; new_long-&gt;value.lval = 10;</pre> </div> </div> </div> Alternatively, you can use the macro <em>ZVAL_LONG</em>: <div class="example-contents"> <div class="ccode"><pre class="ccode">zval *new_long; MAKE_STD_ZVAL(new_long); ZVAL_LONG(new_long, 10);</pre> </div> </div> </p> </div> <div class="sect3" id="internals2.ze1.zendapi.variables.float"> <h4 class="title">Doubles (Floats)</h4> <p class="para"> Doubles are PHP's floats and are as easy to assign as longs, because their value is also contained directly in the union. The member in the <span class="envar">zval.value</span> container is <span class="envar">dval</span>; the corresponding type is <em>IS_DOUBLE</em>. <div class="example-contents"> <div class="ccode"><pre class="ccode">zval *new_double; MAKE_STD_ZVAL(new_double); new_double-&gt;type = IS_DOUBLE; new_double-&gt;value.dval = 3.45;</pre> </div> </div> Alternatively, you can use the macro <em>ZVAL_DOUBLE</em>: <div class="example-contents"> <div class="ccode"><pre class="ccode">zval *new_double; MAKE_STD_ZVAL(new_double); ZVAL_DOUBLE(new_double, 3.45);</pre> </div> </div> </p> </div> <div class="sect3" id="internals2.ze1.zendapi.variables.string"> <h4 class="title">Strings</h4> <p class="para"> Strings need slightly more effort. As mentioned earlier, all strings that will be associated with Zend's internal data structures need to be allocated using Zend's own memory-management functions. Referencing of static strings or strings allocated with standard routines is not allowed. To assign strings, you have to access the structure <span class="envar">str</span> in the <span class="envar">zval.value</span> container. The corresponding type is <em>IS_STRING</em>: <div class="example-contents"> <div class="ccode"><pre class="ccode">zval *new_string; char *string_contents = "This is a new string variable"; MAKE_STD_ZVAL(new_string); new_string-&gt;type = IS_STRING; new_string-&gt;value.str.len = strlen(string_contents); new_string-&gt;value.str.val = estrdup(string_contents);</pre> </div> </div> Note the usage of Zend's <span class="function"><strong>estrdup()</strong></span> here. Of course, you can also use the predefined macro <em>ZVAL_STRING</em>: <div class="example-contents"> <div class="cdata"><pre> zval *new_string; char *string_contents = "This is a new string variable"; MAKE_STD_ZVAL(new_string); ZVAL_STRING(new_string, string_contents, 1); </pre></div> </div> <em>ZVAL_STRING</em> accepts a third parameter that indicates whether the supplied string contents should be duplicated (using <span class="function"><strong>estrdup()</strong></span>). Setting this parameter to <em>1</em> causes the string to be duplicated; <em>0</em> simply uses the supplied pointer for the variable contents. This is most useful if you want to create a new variable referring to a string that's already allocated in Zend internal memory. </p> <p class="para"> If you want to truncate the string at a certain position or you already know its length, you can use <em>ZVAL_STRINGL(zval, string, length, duplicate)</em>, which accepts an explicit string length to be set for the new string. This macro is faster than <em>ZVAL_STRING</em> and also binary-safe. </p> <p class="para"> To create empty strings, set the string length to <em>0</em> and use <em>empty_string</em> as contents: <div class="example-contents"> <div class="ccode"><pre class="ccode">new_string-&gt;type = IS_STRING; new_string-&gt;value.str.len = 0; new_string-&gt;value.str.val = empty_string;</pre> </div> </div> Of course, there's a macro for this as well (<em>ZVAL_EMPTY_STRING</em>): <div class="example-contents"> <div class="ccode"><pre class="ccode">MAKE_STD_ZVAL(new_string); ZVAL_EMPTY_STRING(new_string);</pre> </div> </div> </p> </div> <div class="sect3" id="internals2.ze1.zendapi.variables.boolean"> <h4 class="title">Booleans</h4> <p class="para"> Booleans are created just like longs, but have the type <em>IS_BOOL</em>. Allowed values in <span class="envar">lval</span> are <em>0</em> and <em>1</em>: <div class="example-contents"> <div class="ccode"><pre class="ccode">zval *new_bool; MAKE_STD_ZVAL(new_bool); new_bool-&gt;type = IS_BOOL; new_bool-&gt;value.lval = 1;</pre> </div> </div> The corresponding macros for this type are <em>ZVAL_BOOL</em> (allowing specification of the value) as well as <em>ZVAL_TRUE</em> and <em>ZVAL_FALSE</em> (which explicitly set the value to <em>TRUE</em> and <em>FALSE</em>, respectively). </p> </div> <div class="sect3" id="internals2.ze1.zendapi.variables.array"> <h4 class="title">Arrays</h4> <p class="para"> Arrays are stored using Zend's internal hash tables, which can be accessed using the <span class="function"><strong>zend_hash_*()</strong></span> API. For every array that you want to create, you need a new hash table handle, which will be stored in the <span class="envar">ht</span> member of the <span class="envar">zval.value</span> container. </p> <p class="para"> There's a whole API solely for the creation of arrays, which is extremely handy. To start a new array, you call <span class="function"><strong>array_init()</strong></span>. <div class="example-contents"> <div class="ccode"><pre class="ccode">zval *new_array; MAKE_STD_ZVAL(new_array); array_init(new_array);</pre> </div> </div> <span class="function"><strong>array_init()</strong></span> always returns <em>SUCCESS</em>. </p> <p class="para"> To add new elements to the array, you can use numerous functions, depending on what you want to do. <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.tab.api-assoc-arrays" class="xref">Zend's API for Associative Arrays</a>, <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.tab.api-indexed-arrays" class="xref">Zend's API for Indexed Arrays, Part 1</a> and <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.tab.api-indexed-array-2" class="xref">Zend's API for Indexed Arrays, Part 2</a> describe these functions. All functions return <em>FAILURE</em> on failure and <em>SUCCESS</em> on success. </p> <table id="internals2.ze1.zendapi.tab.api-assoc-arrays" class="doctable table"> <caption><strong>Zend's API for Associative Arrays</strong></caption> <col style="width: *;" /> <col style="width: *;" /> <tbody class="tbody"> <tr> <td>Function</td> <td>Description</td> </tr> <tr> <td> <span class="function"><strong>add_assoc_long(zval *array, char *key, long n);()</strong></span> </td> <td>Adds an element of type <em>long</em>.</td> </tr> <tr> <td> <span class="function"><strong>add_assoc_unset(zval *array, char *key);()</strong></span></td> <td>Adds an unset element.</td> </tr> <tr> <td> <span class="function"><strong>add_assoc_bool(zval *array, char *key, int b);()</strong></span> </td> <td>Adds a Boolean element.</td> </tr> <tr> <td> <span class="function"><strong>add_assoc_resource(zval *array, char *key, int r);()</strong></span> </td> <td>Adds a resource to the array.</td> </tr> <tr> <td> <span class="function"><strong>add_assoc_double(zval *array, char *key, double d);()</strong></span> </td> <td>Adds a floating-point value.</td> </tr> <tr> <td> <span class="function"><strong>add_assoc_string(zval *array, char *key, char *str, int duplicate);()</strong></span> </td> <td> Adds a string to the array. The flag <span class="envar">duplicate</span> specifies whether the string contents have to be copied to Zend internal memory. </td> </tr> <tr> <td> <span class="function"><strong> add_assoc_stringl(zval *array, char *key, char *str, uint length, int duplicate); ()</strong></span> </td> <td> Adds a string with the desired length <span class="envar">length</span> to the array. Otherwise, behaves like <span class="function"><strong>add_assoc_string()</strong></span>. </td> </tr> <tr> <td> <span class="function"><strong>add_assoc_zval(zval *array, char *key, zval *value);()</strong></span></td> <td>Adds a zval to the array. Useful for adding other arrays, objects, streams, etc...</td> </tr> </tbody> </table> <table id="internals2.ze1.zendapi.tab.api-indexed-arrays" class="doctable table"> <caption><strong>Zend's API for Indexed Arrays, Part 1</strong></caption> <col style="width: *;" /> <col style="width: *;" /> <tbody class="tbody"> <tr> <td>Function</td> <td>Description</td> </tr> <tr> <td> <span class="function"><strong>add_index_long(zval *array, uint idx, long n);()</strong></span></td> <td>Adds an element of type <em>long</em>.</td> </tr> <tr> <td> <span class="function"><strong>add_index_unset(zval *array, uint idx);()</strong></span></td> <td>Adds an unset element.</td> </tr> <tr> <td> <span class="function"><strong>add_index_bool(zval *array, uint idx, int b);()</strong></span></td> <td>Adds a Boolean element.</td> </tr> <tr> <td> <span class="function"><strong>add_index_resource(zval *array, uint idx, int r);()</strong></span></td> <td>Adds a resource to the array.</td> </tr> <tr> <td> <span class="function"><strong>add_index_double(zval *array, uint idx, double d);()</strong></span></td> <td>Adds a floating-point value.</td> </tr> <tr> <td> <span class="function"><strong>add_index_string(zval *array, uint idx, char *str, int duplicate);()</strong></span></td> <td>Adds a string to the array. The flag <span class="envar">duplicate</span> specifies whether the string contents have to be copied to Zend internal memory.</td> </tr> <tr> <td> <span class="function"><strong>add_index_stringl(zval *array, uint idx, char *str, uint length, int duplicate);()</strong></span></td> <td>Adds a string with the desired length <span class="envar">length</span> to the array. This function is faster and binary-safe. Otherwise, behaves like <span class="function"><strong>add_index_string()</strong></span>.</td> </tr> <tr> <td> <span class="function"><strong>add_index_zval(zval *array, uint idx, zval *value);()</strong></span></td> <td>Adds a zval to the array. Useful for adding other arrays, objects, streams, etc...</td> </tr> </tbody> </table> <table id="internals2.ze1.zendapi.tab.api-indexed-array-2" class="doctable table"> <caption><strong>Zend's API for Indexed Arrays, Part 2</strong></caption> <col style="width: *;" /> <col style="width: *;" /> <tbody class="tbody"> <tr> <td>Function</td> <td>Description</td> </tr> <tr> <td> <span class="function"><strong>add_next_index_long(zval *array, long n);()</strong></span></td> <td>Adds an element of type <em>long</em>.</td> </tr> <tr> <td> <span class="function"><strong>add_next_index_unset(zval *array);()</strong></span></td> <td>Adds an unset element.</td> </tr> <tr> <td> <span class="function"><strong>add_next_index_bool(zval *array, int b);()</strong></span></td> <td>Adds a Boolean element.</td> </tr> <tr> <td> <span class="function"><strong>add_next_index_resource(zval *array, int r);()</strong></span></td> <td>Adds a resource to the array.</td> </tr> <tr> <td> <span class="function"><strong>add_next_index_double(zval *array, double d);()</strong></span></td> <td>Adds a floating-point value.</td> </tr> <tr> <td> <span class="function"><strong>add_next_index_string(zval *array, char *str, int duplicate);()</strong></span></td> <td>Adds a string to the array. The flag <span class="envar">duplicate</span> specifies whether the string contents have to be copied to Zend internal memory.</td> </tr> <tr> <td> <span class="function"><strong>add_next_index_stringl(zval *array, char *str, uint length, int duplicate);()</strong></span></td> <td>Adds a string with the desired length <span class="envar">length</span> to the array. This function is faster and binary-safe. Otherwise, behaves like <span class="function"><strong>add_index_string()</strong></span>.</td> </tr> <tr> <td> <span class="function"><strong>add_next_index_zval(zval *array, zval *value);()</strong></span></td> <td>Adds a zval to the array. Useful for adding other arrays, objects, streams, etc...</td> </tr> </tbody> </table> <p class="para"> All these functions provide a handy abstraction to Zend's internal hash API. Of course, you can also use the hash functions directly - for example, if you already have a <span class="envar">zval</span> container allocated that you want to insert into an array. This is done using <span class="function"><strong>zend_hash_update()</strong></span> for associative arrays (see <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.example.array-add-assoc" class="xref">Adding an element to an associative array.</a>) and <span class="function"><strong>zend_hash_index_update()</strong></span> for indexed arrays (see <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.example.array-add-indexed" class="xref">Adding an element to an indexed array.</a>): <div class="example" id="internals2.ze1.zendapi.example.array-add-assoc"> <p><strong>Example #11 Adding an element to an associative array.</strong></p> <div class="example-contents"> <div class="ccode"><pre class="ccode">zval *new_array, *new_element; char *key = "element_key"; MAKE_STD_ZVAL(new_array); MAKE_STD_ZVAL(new_element); array_init(new_array); ZVAL_LONG(new_element, 10); if(zend_hash_update(new_array-&gt;value.ht, key, strlen(key) + 1, (void *)&new_element, sizeof(zval *), NULL) == FAILURE) { // do error handling here }</pre> </div> </div> </div> <div class="example" id="internals2.ze1.zendapi.example.array-add-indexed"> <p><strong>Example #12 Adding an element to an indexed array.</strong></p> <div class="example-contents"> <div class="ccode"><pre class="ccode">zval *new_array, *new_element; int key = 2; MAKE_STD_ZVAL(new_array); MAKE_STD_ZVAL(new_element); array_init(new_array); ZVAL_LONG(new_element, 10); if(zend_hash_index_update(new_array-&gt;value.ht, key, (void *)&new_element, sizeof(zval *), NULL) == FAILURE) { // do error handling here }</pre> </div> </div> </div> </p> <p class="para"> To emulate the functionality of <span class="function"><strong>add_next_index_*()</strong></span>, you can use this: </p> <div class="example-contents"> <div class="ccode"><pre class="ccode">zend_hash_next_index_insert(ht, zval **new_element, sizeof(zval *), NULL)</pre> </div> </div> <p class="para"> <em class="emphasis">Note:</em> To return arrays from a function, use <span class="function"><strong>array_init()</strong></span> and all following actions on the predefined variable <span class="envar">return_value</span> (given as argument to your exported function; see the earlier discussion of the call interface). You do not have to use <em>MAKE_STD_ZVAL</em> on this. </p> <p class="para"> <em class="emphasis">Tip:</em> To avoid having to write <em>new_array->value.ht</em> every time, you can use <em>HASH_OF(new_array)</em>, which is also recommended for compatibility and style reasons. </p> </div> <div class="sect3" id="internals2.ze1.zendapi.variables.object"> <h4 class="title">Objects</h4> <p class="para"> Since objects can be converted to arrays (and vice versa), you might have already guessed that they have a lot of similarities to arrays in PHP. Objects are maintained with the same hash functions, but there's a different API for creating them. </p> <p class="para"> To initialize an object, you use the function <span class="function"><strong>object_init()</strong></span>: <div class="example-contents"> <div class="ccode"><pre class="ccode">zval *new_object; MAKE_STD_ZVAL(new_object); if(object_init(new_object) != SUCCESS) { // do error handling here }</pre> </div> </div> You can use the functions described in <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.tab.object-creation" class="xref">Zend's API for Object Creation</a> to add members to your object. </p> <table id="internals2.ze1.zendapi.tab.object-creation" class="doctable table"> <caption><strong>Zend's API for Object Creation</strong></caption> <col style="width: 1.24*;" /> <col style="width: 1.00*;" /> <tbody class="tbody"> <tr> <td>Function</td> <td>Description</td> </tr> <tr> <td> <span class="function"><strong>add_property_long(zval *object, char *key, long l);()</strong></span></td> <td>Adds a long to the object.</td> </tr> <tr> <td> <span class="function"><strong>add_property_unset(zval *object, char *key);()</strong></span></td> <td>Adds an unset property to the object.</td> </tr> <tr> <td> <span class="function"><strong>add_property_bool(zval *object, char *key, int b);()</strong></span></td> <td>Adds a Boolean to the object.</td> </tr> <tr> <td> <span class="function"><strong>add_property_resource(zval *object, char *key, long r);()</strong></span></td> <td>Adds a resource to the object.</td> </tr> <tr> <td> <span class="function"><strong>add_property_double(zval *object, char *key, double d);()</strong></span></td> <td>Adds a double to the object.</td> </tr> <tr> <td> <span class="function"><strong>add_property_string(zval *object, char *key, char *str, int duplicate);()</strong></span></td> <td>Adds a string to the object.</td> </tr> <tr> <td> <span class="function"><strong>add_property_stringl(zval *object, char *key, char *str, uint length, int duplicate);()</strong></span></td> <td>Adds a string of the specified length to the object. This function is faster than <span class="function"><strong>add_property_string()</strong></span> and also binary-safe.</td> </tr> <tr> <td> <span class="function"><strong>add_property_zval(zval *obect, char *key, zval *container):()</strong></span> </td> <td> Adds a <em>zval</em> container to the object. This is useful if you have to add properties which aren't simple types like integers or strings but arrays or other objects. </td> </tr> </tbody> </table> </div> <div class="sect3" id="zend.variables.resource"> <h4 class="title">Resources</h4> <p class="para"> Resources are a special kind of data type in PHP. The term <em class="emphasis">resources</em> doesn't really refer to any special kind of data, but to an abstraction method for maintaining any kind of information. Resources are kept in a special resource list within Zend. Each entry in the list has a correspondending type definition that denotes the kind of resource to which it refers. Zend then internally manages all references to this resource. Access to a resource is never possible directly - only via a provided API. As soon as all references to a specific resource are lost, a corresponding shutdown function is called. </p> <p class="para"> For example, resources are used to store database links and file descriptors. The <em class="emphasis">de facto</em> standard implementation can be found in the MySQL module, but other modules such as the Oracle module also make use of resources. <blockquote class="note"><p><strong class="note">Note</strong>: <p class="para"> In fact, a resource can be a pointer to anything you need to handle in your functions (e.g. pointer to a structure) and the user only has to pass a single resource variable to your function. </p> </p></blockquote> </p> <p class="para"> To create a new resource you need to register a resource destruction handler for it. Since you can store any kind of data as a resource, Zend needs to know how to free this resource if its not longer needed. This works by registering your own resource destruction handler to Zend which in turn gets called by Zend whenever your resource can be freed (whether manually or automatically). Registering your resource handler within Zend returns you the <em class="emphasis">resource type handle</em> for that resource. This handle is needed whenever you want to access a resource of this type later and is most of time stored in a global static variable within your extension. There is no need to worry about thread safety here because you only register your resource handler once during module initialization. </p> <p class="para"> The Zend function to register your resource handler is defined as: <div class="example-contents"> <div class="ccode"><pre class="ccode">ZEND_API int zend_register_list_destructors_ex(rsrc_dtor_func_t ld, rsrc_dtor_func_t pld, char *type_name, int module_number);</pre> </div> </div> </p> <p class="para"> There are two different kinds of resource destruction handlers you can pass to this function: a handler for normal resources and a handler for persistent resources. Persistent resources are for example used for database connection. When registering a resource, either of these handlers must be given. For the other handler just pass <em>NULL</em>. </p> <p class="para"> <span class="function"><strong>zend_register_list_destructors_ex()</strong></span> accepts the following parameters: <table class="doctable informaltable"> <col style="width: 1.00*;" /> <col style="width: 5.00*;" /> <tbody class="tbody"> <tr> <td><em>ld</em></td> <td>Normal resource destruction handler callback</td> </tr> <tr> <td><em>pld</em></td> <td>Pesistent resource destruction handler callback</td> </tr> <tr> <td><em>type_name</em></td> <td>A string specifying the name of your resource. It's always a good thing to specify a unique name within PHP for the resource type so when the user for example calls <em>var_dump($resource);</em> he also gets the name of the resource.</td> </tr> <tr> <td><em>module_number</em></td> <td>The <em>module_number</em> is automatically available in your <em>PHP_MINIT_FUNCTION</em> function and therefore you just pass it over.</td> </tr> </tbody> </table> The return value is a unique integer ID for your <em class="emphasis">resource type</em>. </p> <p class="para"> The resource destruction handler (either normal or persistent resources) has the following prototype: <div class="example-contents"><div class="cdata"><pre>void resource_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC);</pre></div></div> The passed <em>rsrc</em> is a pointer to the following structure: <div class="example-contents"> <div class="ccode"><pre class="ccode">typedef struct _zend_rsrc_list_entry { void *ptr; int type; int refcount; } zend_rsrc_list_entry;</pre> </div> </div> The member <em>void *ptr</em> is the actual pointer to your resource. </p> <p class="para"> Now we know how to start things, we define our own resource we want register within Zend. It is only a simple structure with two integer members: <div class="example-contents"> <div class="ccode"><pre class="ccode">typedef struct { int resource_link; int resource_type; } my_resource;</pre> </div> </div> Our resource destruction handler is probably going to look something like this: <div class="example-contents"> <div class="ccode"><pre class="ccode">void my_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC) { // You most likely cast the void pointer to your structure type my_resource *my_rsrc = (my_resource *) rsrc->ptr; // Now do whatever needs to be done with you resource. Closing // Files, Sockets, freeing additional memory, etc. // Also, don't forget to actually free the memory for your resource too! do_whatever_needs_to_be_done_with_the_resource(my_rsrc); }</pre> </div> </div> <blockquote class="note"><p><strong class="note">Note</strong>: <p class="para">One important thing to mention: If your resource is a rather complex structure which also contains pointers to memory you allocated during runtime you have to free them <em class="emphasis">before</em> freeing the resource itself! </p> </p></blockquote> </p> <p class="para"> Now that we have defined <ol type="1"> <li class="listitem"><p class="para">what our resource is and</p></li> <li class="listitem"><p class="para">our resource destruction handler</p></li> </ol> we can go on and do the rest of the steps: <ol type="1"> <li class="listitem"><p class="para">create a global variable within the extension holding the resource ID so it can be accessed from every function which needs it</p></li> <li class="listitem"><p class="para">define the resource name</p></li> <li class="listitem"><p class="para">write the resource destruction handler</p></li> <li class="listitem"><p class="para">and finally register the handler</p></li> </ol> <div class="example-contents"> <div class="ccode"><pre class="ccode">// Somewhere in your extension, define the variable for your registered resources. // If you wondered what 'le' stands for: it simply means 'list entry'. static int le_myresource; // It's nice to define your resource name somewhere #define le_myresource_name "My type of resource" [...] // Now actually define our resource destruction handler void my_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC) { my_resource *my_rsrc = (my_resource *) rsrc->ptr; do_whatever_needs_to_be_done_with_the_resource(my_rsrc); } [...] PHP_MINIT_FUNCTION(my_extension) { // Note that 'module_number' is already provided through the // PHP_MINIT_FUNCTION() function definition. le_myresource = zend_register_list_destructors_ex(my_destruction_handler, NULL, le_myresource_name, module_number); // You can register additional resources, initialize // your global vars, constants, whatever. }</pre> </div> </div> </p> <p class="para"> To actually register a new resource you use can either use the <span class="function"><strong>zend_register_resource()</strong></span> function or the <span class="function"><strong>ZEND_REGISTER_RESOURE()</strong></span> macro, both defined in zend_list.h. Although the arguments for both map 1:1 it's a good idea to always use macros to be upwards compatible: <div class="example-contents"> <div class="ccode"><pre class="ccode">int ZEND_REGISTER_RESOURCE(zval *rsrc_result, void *rsrc_pointer, int rsrc_type);</pre> </div> </div> <table class="doctable informaltable"> <col style="width: 1.00*;" /> <col style="width: 5.00*;" /> <tbody class="tbody"> <tr> <td><em>rsrc_result</em></td> <td>This is an already initialized <em>zval *</em> container.</td> </tr> <tr> <td><em>rsrc_pointer</em></td> <td>Your resource pointer you want to store.</td> </tr> <tr> <td><em>rsrc_type</em></td> <td>The type which you received when you registered the resource destruction handler. If you followed the naming scheme this would be <em>le_myresource</em>.</td> </tr> </tbody> </table> The return value is a unique integer identifier for that resource. </p> <p class="para"> What is really going on when you register a new resource is it gets inserted in an internal list in Zend and the result is just stored in the given <em>zval *</em> container: <div class="example-contents"> <div class="ccode"><pre class="ccode">rsrc_id = zend_list_insert(rsrc_pointer, rsrc_type); if (rsrc_result) { rsrc_result->value.lval = rsrc_id; rsrc_result->type = IS_RESOURCE; } return rsrc_id;</pre> </div> </div> The returned <em>rsrc_id</em> uniquely identifies the newly registered resource. You can use the macro <em>RETURN_RESOURE</em> to return it to the user: <div class="example-contents"><div class="cdata"><pre> RETURN_RESOURCE(rsrc_id)</pre></div></div> <blockquote class="note"><p><strong class="note">Note</strong>: <p class="para">It is common practice that if you want to return the resource immediately to the user you specify the <em>return_value</em> as the <em>zval *</em> container. </p> </p></blockquote> </p> <p class="para"> Zend now keeps track of all references to this resource. As soon as all references to the resource are lost, the destructor that you previously registered for this resource is called. The nice thing about this setup is that you don't have to worry about memory leakages introduced by allocations in your module - just register all memory allocations that your calling script will refer to as resources. As soon as the script decides it doesn't need them anymore, Zend will find out and tell you. </p> <p class="para"> Now that the user got his resource, at some point he is passing it back to one of your functions. The <span class="envar">value.lval</span> inside the <em>zval *</em> container contains the key to your resource and thus can be used to fetch the resource with the following macro: <em>ZEND_FETCH_RESOURCE</em>: <div class="example-contents"> <div class="ccode"><pre class="ccode">ZEND_FETCH_RESOURCE(rsrc, rsrc_type, rsrc_id, default_rsrc_id, resource_type_name, resource_type)</pre> </div> </div> <table class="doctable informaltable"> <col style="width: 1.00*;" /> <col style="width: 5.00*;" /> <tbody class="tbody"> <tr> <td><em>rsrc</em></td> <td>This is your pointer which will point to your previously registered resource.</td> </tr> <tr> <td><em>rsrc_type</em></td> <td>This is the typecast argument for your pointer, e.g. <em>myresource *</em>.</td> </tr> <tr> <td><em>rsrc_id</em></td> <td>This is the address of the <em>zval *</em>container the user passed to your function, e.g. <em>&z_resource</em> if <em>zval *z_resource</em> is given.</td> </tr> <tr> <td><em>default_rsrc_id</em></td> <td>This integer specifies the default resource <em>ID</em> if no resource could be fetched or -1.</td> </tr> <tr> <td><em>resource_type_name</em></td> <td>This is the name of the requested resource. It's a string and is used when the resource can't be found or is invalid to form a meaningful error message.</td> </tr> <tr> <td><em>resource_type</em></td> <td>The <em>resource_type</em> you got back when registering the resource destruction handler. In our example this was <span class="envar">le_myresource</span>.</td> </tr> </tbody> </table> This macro has no return value. It is for the developers convenience and takes care of TSRMLS arguments passing and also does check if the resource could be fetched. It throws a warning message and returns the current PHP function with <em>NULL</em> if there was a problem retrieving the resource. </p> <p class="para"> To force removal of a resource from the list, use the function <span class="function"><strong>zend_list_delete()</strong></span>. You can also force the reference count to increase if you know that you're creating another reference for a previously allocated value (for example, if you're automatically reusing a default database link). For this case, use the function <span class="function"><strong>zend_list_addref()</strong></span>. To search for previously allocated resource entries, use <span class="function"><strong>zend_list_find()</strong></span>. The complete API can be found in <var class="filename">zend_list.h</var>. </p> </div> <div class="sect3" id="internals2.ze1.zendapi.variables.global"> <h4 class="title">Macros for Automatic Global Variable Creation</h4> <p class="para"> In addition to the macros discussed earlier, a few macros allow easy creation of simple global variables. These are nice to know in case you want to introduce global flags, for example. This is somewhat bad practice, but Table <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.tab.macros-global-vars" class="xref">Macros for Global Variable Creation</a> describes macros that do exactly this task. They don't need any <span class="envar">zval</span> allocation; you simply have to supply a variable name and value. </p> <table id="internals2.ze1.zendapi.tab.macros-global-vars" class="doctable table"> <caption><strong>Macros for Global Variable Creation</strong></caption> <col style="width: *;" /> <col style="width: *;" /> <tbody class="tbody"> <tr> <td>Macro</td> <td>Description</td> </tr> <tr> <td><em>SET_VAR_STRING(name, value)</em></td> <td>Creates a new string.</td> </tr> <tr> <td><em>SET_VAR_STRINGL(name, value, length)</em></td> <td>Creates a new string of the specified length. This macro is faster than <em>SET_VAR_STRING</em> and also binary-safe.</td> </tr> <tr> <td><em>SET_VAR_LONG(name, value)</em></td> <td>Creates a new long.</td> </tr> <tr> <td><em>SET_VAR_DOUBLE(name, value)</em></td> <td>Creates a new double.</td> </tr> </tbody> </table> </div> <div class="sect3" id="internals2.ze1.zendapi.variables.constant"> <h4 class="title">Creating Constants</h4> <p class="para"> Zend supports the creation of true constants (as opposed to regular variables). Constants are accessed without the typical dollar sign (<em>$</em>) prefix and are available in all scopes. Examples include <em>TRUE</em> and <em>FALSE</em>, to name just two. </p> <p class="para"> To create your own constants, you can use the macros in <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.tab.create-const" class="xref">Macros for Creating Constants</a>. All the macros create a constant with the specified name and value. </p> <p class="para"> You can also specify flags for each constant: <ul class="itemizedlist"> <li class="listitem"> <p class="para"> <em>CONST_CS</em> - This constant's name is to be treated as case sensitive. </p> </li> <li class="listitem"> <p class="para"> <em>CONST_PERSISTENT</em> - This constant is persistent and won't be "forgotten" when the current process carrying this constant shuts down. </p> </li> </ul> To use the flags, combine them using a inary OR: <div class="example-contents"><div class="cdata"><pre> // register a new constant of type "long" REGISTER_LONG_CONSTANT("NEW_MEANINGFUL_CONSTANT", 324, CONST_CS | CONST_PERSISTENT); </pre></div></div> There are two types of macros - <em>REGISTER_*_CONSTANT</em> and<em>REGISTER_MAIN_*_CONSTANT</em>. The first type creates constants bound to the current module. These constants are dumped from the symbol table as soon as the module that registered the constant is unloaded from memory. The second type creates constants that remain in the symbol table independently of the module. </p> <table id="internals2.ze1.zendapi.tab.create-const" class="doctable table"> <caption><strong>Macros for Creating Constants</strong></caption> <col style="width: 1.53*;" /> <col style="width: 1.00*;" /> <tbody class="tbody"> <tr> <td>Macro</td> <td>Description</td> </tr> <tr> <td> <em>REGISTER_LONG_CONSTANT(name, value, flags)</em> <em>REGISTER_MAIN_LONG_CONSTANT(name, value, flags)</em> </td> <td>Registers a new constant of type long.</td> </tr> <tr> <td> <em>REGISTER_DOUBLE_CONSTANT(name, value, flags)</em> <em>REGISTER_MAIN_DOUBLE_CONSTANT(name, value, flags)</em> </td> <td>Registers a new constant of type double.</td> </tr> <tr> <td> <em>REGISTER_STRING_CONSTANT(name, value, flags)</em> <em>REGISTER_MAIN_STRING_CONSTANT(name, value, flags)</em> </td> <td> Registers a new constant of type string. The specified string must reside in Zend's internal memory.</td> </tr> <tr> <td> <em>REGISTER_STRINGL_CONSTANT(name, value, length, flags)</em> <em>REGISTER_MAIN_STRINGL_CONSTANT(name, value, length, flags)</em> </td> <td>Registers a new constant of type string. The string length is explicitly set to <span class="envar">length</span>. The specified string must reside in Zend's internal memory.</td> </tr> </tbody> </table> </div> </div> <div class="sect2" id="internals2.ze1.zendapi.copy-constructor"> <h3 class="title">Duplicating Variable Contents: The Copy Constructor</h3> <p class="para"> Sooner or later, you may need to assign the contents of one <span class="envar">zval</span> container to another. This is easier said than done, since the <span class="envar">zval</span> container doesn't contain only type information, but also references to places in Zend's internal data. For example, depending on their size, arrays and objects may be nested with lots of hash table entries. By assigning one <span class="envar">zval</span> to another, you avoid duplicating the hash table entries, using only a reference to them (at most). </p> <p class="para"> To copy this complex kind of data, use the <em class="emphasis">copy constructor</em>. Copy constructors are typically defined in languages that support operator overloading, with the express purpose of copying complex types. If you define an object in such a language, you have the possibility of overloading the "=" operator, which is usually responsible for assigning the contents of the rvalue (result of the evaluation of the right side of the operator) to the lvalue (same for the left side). </p> <p class="para"> <em class="emphasis">Overloading</em> means assigning a different meaning to this operator, and is usually used to assign a function call to an operator. Whenever this operator would be used on such an object in a program, this function would be called with the lvalue and rvalue as parameters. Equipped with that information, it can perform the operation it intends the "=" operator to have (usually an extended form of copying). </p> <p class="para"> This same form of "extended copying" is also necessary for PHP's <span class="envar">zval</span> containers. Again, in the case of an array, this extended copying would imply re-creation of all hash table entries relating to this array. For strings, proper memory allocation would have to be assured, and so on. </p> <p class="para"> Zend ships with such a function, called <span class="function"><strong>zend_copy_ctor()</strong></span> (the previous PHP equivalent was <span class="function"><strong>pval_copy_constructor()</strong></span>). </p> <p class="para"> A most useful demonstration is a function that accepts a complex type as argument, modifies it, and then returns the argument: </p> <div class="example-contents"> <div class="ccode"><pre class="ccode">zval *parameter; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &parameter) == FAILURE) return; } // do modifications to the parameter here // now we want to return the modified container: *return_value = *parameter; zval_copy_ctor(return_value);</pre> </div> </div> <p class="para"> The first part of the function is plain-vanilla argument retrieval. After the (left out) modifications, however, it gets interesting: The container of <span class="envar">parameter</span> is assigned to the (predefined) <span class="envar">return_value</span> container. Now, in order to effectively duplicate its contents, the copy constructor is called. The copy constructor works directly with the supplied argument, and the standard return values are <em>FAILURE</em> on failure and <em>SUCCESS</em> on success. </p> <p class="para"> If you omit the call to the copy constructor in this example, both <span class="envar">parameter</span> and <span class="envar">return_value</span> would point to the same internal data, meaning that <span class="envar">return_value</span> would be an illegal additional reference to the same data structures. Whenever changes occurred in the data that <span class="envar">parameter</span> points to, <span class="envar">return_value</span> might be affected. Thus, in order to create separate copies, the copy constructor must be used. </p> <p class="para"> The copy constructor's counterpart in the Zend API, the destructor <span class="function"><strong>zval_dtor()</strong></span>, does the opposite of the constructor. </p> </div> <div class="sect2" id="internals2.ze1.zendapi.returning"> <h3 class="title">Returning Values</h3> <p class="para"> Returning values from your functions to PHP was described briefly in an earlier section; this section gives the details. Return values are passed via the <span class="envar">return_value</span> variable, which is passed to your functions as argument. The <span class="envar">return_value</span> argument consists of a <span class="envar">zval</span> container (see the earlier discussion of the call interface) that you can freely modify. The container itself is already allocated, so you don't have to run <em>MAKE_STD_ZVAL</em> on it. Instead, you can access its members directly. </p> <p class="para"> To make returning values from functions easier and to prevent hassles with accessing the internal structures of the <span class="envar">zval</span> container, a set of predefined macros is available (as usual). These macros automatically set the correspondent type and value, as described in <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.tab.return" class="xref">Predefined Macros for Returning Values from a Function</a> and <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.tab.retval" class="xref">Predefined Macros for Setting the Return Value of a Function</a>. </p> <blockquote class="note"><p><strong class="note">Note</strong>: <p class="para"> The macros in <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.tab.return" class="xref">Predefined Macros for Returning Values from a Function</a> automatically <em class="emphasis">return</em> from your function, those in <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.tab.retval" class="xref">Predefined Macros for Setting the Return Value of a Function</a> only <em class="emphasis">set</em> the return value; they don't return from your function. </p> </p></blockquote> <table id="internals2.ze1.zendapi.tab.return" class="doctable table"> <caption><strong>Predefined Macros for Returning Values from a Function</strong></caption> <col style="width: *;" /> <col style="width: *;" /> <tbody class="tbody"> <tr> <td>Macro</td> <td>Description</td> </tr> <tr> <td><em>RETURN_RESOURCE(resource)</em></td> <td>Returns a resource.</td> </tr> <tr> <td><em>RETURN_BOOL(bool)</em></td> <td>Returns a Boolean.</td> </tr> <tr> <td><em>RETURN_NULL()</em></td> <td>Returns nothing (a NULL value).</td> </tr> <tr> <td><em>RETURN_LONG(long)</em></td> <td>Returns a long.</td> </tr> <tr> <td><em>RETURN_DOUBLE(double)</em></td> <td>Returns a double.</td> </tr> <tr> <td> <em>RETURN_STRING(string, duplicate)</em> </td> <td> Returns a string. The <span class="envar">duplicate</span> flag indicates whether the string should be duplicated using <span class="function"><strong>estrdup()</strong></span>. </td> </tr> <tr> <td> <em>RETURN_STRINGL(string, length, duplicate)</em> </td> <td> Returns a string of the specified length; otherwise, behaves like <em>RETURN_STRING</em>. This macro is faster and binary-safe, however. </td> </tr> <tr> <td><em>RETURN_EMPTY_STRING()</em></td> <td>Returns an empty string.</td> </tr> <tr> <td><em>RETURN_FALSE</em></td> <td>Returns Boolean false.</td> </tr> <tr> <td><em>RETURN_TRUE</em></td> <td>Returns Boolean true.</td> </tr> </tbody> </table> <table id="internals2.ze1.zendapi.tab.retval" class="doctable table"> <caption><strong>Predefined Macros for Setting the Return Value of a Function</strong></caption> <col style="width: *;" /> <col style="width: *;" /> <tbody class="tbody"> <tr> <td>Macro</td> <td>Description</td> </tr> <tr> <td><em>RETVAL_RESOURCE(resource)</em></td> <td>Sets the return value to the specified resource.</td> </tr> <tr> <td><em>RETVAL_BOOL(bool)</em></td> <td>Sets the return value to the specified Boolean value.</td> </tr> <tr> <td><em>RETVAL_NULL</em></td> <td>Sets the return value to NULL.</td> </tr> <tr> <td><em>RETVAL_LONG(long)</em></td> <td> Sets the return value to the specified long. </td> </tr> <tr> <td><em>RETVAL_DOUBLE(double)</em></td> <td> Sets the return value to the specified double. </td> </tr> <tr> <td> <em>RETVAL_STRING(string, duplicate)</em> </td> <td> Sets the return value to the specified string and duplicates it to Zend internal memory if desired (see also <em>RETURN_STRING</em>). </td> </tr> <tr> <td> <em>RETVAL_STRINGL(string, length, duplicate)</em> </td> <td> Sets the return value to the specified string and forces the length to become <span class="envar">length</span> (see also <em>RETVAL_STRING</em>). This macro is faster and binary-safe, and should be used whenever the string length is known. </td> </tr> <tr> <td> <em>RETVAL_EMPTY_STRING</em> </td> <td> Sets the return value to an empty string. </td> </tr> <tr> <td><em>RETVAL_FALSE</em></td> <td> Sets the return value to Boolean false. </td> </tr> <tr> <td><em>RETVAL_TRUE</em></td> <td> Sets the return value to Boolean true. </td> </tr> </tbody> </table> <p class="para"> Complex types such as arrays and objects can be returned by using <span class="function"><strong>array_init()</strong></span> and <span class="function"><strong>object_init()</strong></span>, as well as the corresponding hash functions on <span class="envar">return_value</span>. Since these types cannot be constructed of trivial information, there are no predefined macros for them. </p> </div> <div class="sect2" id="internals2.ze1.zendapi.printing"> <h3 class="title">Printing Information</h3> <p class="para"> Often it's necessary to print messages to the output stream from your module, just as <span class="function"><a href="function.print.html" class="function">print</a></span> would be used within a script. PHP offers functions for most generic tasks, such as printing warning messages, generating output for <span class="function"><a href="function.phpinfo.html" class="function">phpinfo()</a></span>, and so on. The following sections provide more details. Examples of these functions can be found on the CD-ROM. </p> <div class="sect3" id="internals2.ze1.zendapi.printing.zend-printf"> <h4 class="title"> <span class="function"><strong>zend_printf()</strong></span></h4> <p class="para"> <span class="function"><strong>zend_printf()</strong></span> works like the standard <span class="function"><a href="function.printf.html" class="function">printf()</a></span>, except that it prints to Zend's output stream. </p> </div> <div class="sect3" id="internals2.ze1.zendapi.printing.zend-error"> <h4 class="title"> <span class="function"><strong>zend_error()</strong></span></h4> <p class="para"> <span class="function"><strong>zend_error()</strong></span> can be used to generate error messages. This function accepts two arguments; the first is the error type (see <var class="filename">zend_errors.h</var>), and the second is the error message. <div class="example-contents"> <div class="ccode"><pre class="ccode">zend_error(E_WARNING, "This function has been called with empty arguments");</pre> </div> </div> <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.tab.error-messages" class="xref">Zend's Predefined Error Messages.</a> shows a list of possible values (see <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.fig.warning-messages" class="link">below</a>). These values are also referred to in <var class="filename">php.ini</var>. Depending on which error type you choose, your messages will be logged. <table id="internals2.ze1.zendapi.tab.error-messages" class="doctable table"> <caption><strong>Zend's Predefined Error Messages.</strong></caption> <col style="width: 1.00*;" /> <col style="width: 1.36*;" /> <tbody class="tbody"> <tr> <td>Error</td> <td>Description</td> </tr> <tr> <td><strong><code>E_ERROR</code></strong></td> <td> Signals an error and terminates execution of the script immediately.</td> </tr> <tr> <td><strong><code>E_WARNING</code></strong></td> <td> Signals a generic warning. Execution continues. </td> </tr> <tr> <td><strong><code>E_PARSE</code></strong></td> <td> Signals a parser error. Execution continues. </td> </tr> <tr> <td><strong><code>E_NOTICE</code></strong></td> <td> Signals a notice. Execution continues. Note that by default the display of this type of error messages is turned off in <var class="filename">php.ini</var>. </td> </tr> <tr> <td><strong><code>E_CORE_ERROR</code></strong></td> <td> Internal error by the core; shouldn't be used by user-written modules. </td> </tr> <tr> <td><strong><code>E_COMPILE_ERROR</code></strong></td> <td> Internal error by the compiler; shouldn't be used by user-written modules. </td> </tr> <tr> <td><strong><code>E_COMPILE_WARNING</code></strong></td> <td> Internal warning by the compiler; shouldn't be used by user-written modules. </td> </tr> </tbody> </table> <div class="mediaobject"> <div class="imageobject"> <img src="images/befd863081615f539082d9ff76bf7b39-zend.07-warning-messages.png" alt="Display of warning messages in the browser." width="322" height="218" /> </div> </div> </p> </div> <div class="sect3" id="internals2.ze1.zendapi.printing.phpinfo"> <h4 class="title">Including Output in <span class="function"><a href="function.phpinfo.html" class="function">phpinfo()</a></span></h4> <p class="para"> After creating a real module, you'll want to show information about the module in <span class="function"><a href="function.phpinfo.html" class="function">phpinfo()</a></span> (in addition to the module name, which appears in the module list by default). PHP allows you to create your own section in the <span class="function"><a href="function.phpinfo.html" class="function">phpinfo()</a></span> output with the <em>ZEND_MINFO()</em> function. This function should be placed in the module descriptor block (discussed earlier) and is always called whenever a script calls <span class="function"><a href="function.phpinfo.html" class="function">phpinfo()</a></span>. </p> <p class="para"> PHP automatically prints a section in <span class="function"><a href="function.phpinfo.html" class="function">phpinfo()</a></span> for you if you specify the <em>ZEND_MINFO</em> function, including the module name in the heading. Everything else must be formatted and printed by you. </p> <p class="para"> Typically, you can print an HTML table header using <span class="function"><strong>php_info_print_table_start()</strong></span> and then use the standard functions <span class="function"><strong>php_info_print_table_header()</strong></span> and <span class="function"><strong>php_info_print_table_row()</strong></span>. As arguments, both take the number of columns (as integers) and the column contents (as strings). <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.example.phpinfo" class="xref">Source code and screenshot for output in phpinfo.</a> shows a source example and its output. To print the table footer, use <span class="function"><strong>php_info_print_table_end()</strong></span>. </p> <div class="example" id="internals2.ze1.zendapi.example.phpinfo"> <p><strong>Example #13 Source code and screenshot for output in <span class="function"><a href="function.phpinfo.html" class="function">phpinfo()</a></span>. </strong></p> <div class="example-contents"> <div class="ccode"><pre class="ccode">php_info_print_table_start(); php_info_print_table_header(2, "First column", "Second column"); php_info_print_table_row(2, "Entry in first row", "Another entry"); php_info_print_table_row(2, "Just to fill", "another row here"); php_info_print_table_end();</pre> </div> </div> <div class="mediaobject"> <div class="imageobject"> <img src="images/befd863081615f539082d9ff76bf7b39-zend.08-phpinfo-output.png" alt="Output of phpinfo()" width="691" height="585" /> </div> </div> </div> </div> <div class="sect3" id="internals2.ze1.zendapi.printing.execution"> <h4 class="title">Execution Information</h4> <p class="para"> You can also print execution information, such as the current file being executed. The name of the function currently being executed can be retrieved using the function <span class="function"><strong>get_active_function_name()</strong></span>. This function returns a pointer to the function name and doesn't accept any arguments. To retrieve the name of the file currently being executed, use <span class="function"><strong>zend_get_executed_filename()</strong></span>. This function accesses the executor globals, which are passed to it using the <em>TSRMLS_C</em> macro. The executor globals are automatically available to every function that's called directly by Zend (they're part of the <em>INTERNAL_FUNCTION_PARAMETERS</em> described earlier in this chapter). If you want to access the executor globals in another function that doesn't have them available automatically, call the macro <em>TSRMLS_FETCH()</em> once in that function; this will introduce them to your local scope. </p> <p class="para"> Finally, the line number currently being executed can be retrieved using the function <span class="function"><strong>zend_get_executed_lineno()</strong></span>. This function also requires the executor globals as arguments. For examples of these functions, see <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.example.exec-info" class="xref">Printing execution information.</a>. </p> <div class="example" id="internals2.ze1.zendapi.example.exec-info"> <p><strong>Example #14 Printing execution information.</strong></p> <div class="example-contents"> <div class="ccode"><pre class="ccode">zend_printf("The name of the current function is %s&lt;br&gt;", get_active_function_name(TSRMLS_C)); zend_printf("The file currently executed is %s&lt;br&gt;", zend_get_executed_filename(TSRMLS_C)); zend_printf("The current line being executed is %i&lt;br&gt;", zend_get_executed_lineno(TSRMLS_C));</pre> </div> </div> <div class="mediaobject"> <div class="imageobject"> <img src="images/befd863081615f539082d9ff76bf7b39-zend.09-execution-info.png" alt="Printing execution information" width="477" height="268" /> </div> </div> </div> </div> </div> <div class="sect2" id="internals2.ze1.zendapi.startup-and-shutdown"> <h3 class="title">Startup and Shutdown Functions</h3> <p class="para"> Startup and shutdown functions can be used for one-time initialization and deinitialization of your modules. As discussed earlier in this chapter (see the description of the Zend module descriptor block), there are module, and request startup and shutdown events. </p> <p class="para"> The module startup and shutdown functions are called whenever a module is loaded and needs initialization; the request startup and shutdown functions are called every time a request is processed (meaning that a file is being executed). </p> <p class="para"> For dynamic extensions, module and request startup/shutdown events happen at the same time. </p> <p class="para"> Declaration and implementation of these functions can be done with macros; see the earlier section "Declaration of the Zend Module Block" for details. </p> </div> <div class="sect2" id="internals2.ze1.zendapi.calling-user-functions"> <h3 class="title">Calling User Functions</h3> <p class="para"> You can call user functions from your own modules, which is very handy when implementing callbacks; for example, for array walking, searching, or simply for event-based programs. </p> <p class="para"> User functions can be called with the function <span class="function"><strong>call_user_function_ex()</strong></span>. It requires a hash value for the function table you want to access, a pointer to an object (if you want to call a method), the function name, return value, number of arguments, argument array, and a flag indicating whether you want to perform zval separation. </p> <div class="example-contents"> <div class="ccode"><pre class="ccode">ZEND_API int call_user_function_ex(HashTable *function_table, zval *object, zval *function_name, zval **retval_ptr_ptr, int param_count, zval **params[], int no_separation);</pre> </div> </div> <p class="para"> Note that you don't have to specify both <span class="envar">function_table</span> and <span class="envar">object</span>; either will do. If you want to call a method, you have to supply the object that contains this method, in which case <span class="function"><strong>call_user_function()</strong></span>automatically sets the function table to this object's function table. Otherwise, you only need to specify <span class="envar">function_table</span> and can set <span class="envar">object</span> to <em>NULL</em>. </p> <p class="para"> Usually, the default function table is the "root" function table containing all function entries. This function table is part of the compiler globals and can be accessed using the macro <em>CG</em>. To introduce the compiler globals to your function, call the macro <em>TSRMLS_FETCH</em> once. </p> <p class="para"> The function name is specified in a <span class="envar">zval</span> container. This might be a bit surprising at first, but is quite a logical step, since most of the time you'll accept function names as parameters from calling functions within your script, which in turn are contained in <span class="envar">zval</span> containers again. Thus, you only have to pass your arguments through to this function. This <span class="envar">zval</span> must be of type <em>IS_STRING</em>. </p> <p class="para"> The next argument consists of a pointer to the return value. You don't have to allocate memory for this container; the function will do so by itself. However, you have to destroy this container (using <span class="function"><strong>zval_dtor()</strong></span>) afterward! </p> <p class="para"> Next is the parameter count as integer and an array containing all necessary parameters. The last argument specifies whether the function should perform zval separation - this should always be set to <em>0</em>. If set to <em>1</em>, the function consumes less memory but fails if any of the parameters need separation. </p> <p class="para"> <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.example.call-user-func" class="xref">Calling user functions.</a> shows a small demonstration of calling a user function. The code calls a function that's supplied to it as argument and directly passes this function's return value through as its own return value. Note the use of the constructor and destructor calls at the end - it might not be necessary to do it this way here (since they should be separate values, the assignment might be safe), but this is bulletproof. </p> <div class="example" id="internals2.ze1.zendapi.example.call-user-func"> <p><strong>Example #15 Calling user functions.</strong></p> <div class="example-contents"> <div class="ccode"><pre class="ccode">zval **function_name; zval *retval; if((ZEND_NUM_ARGS() != 1) || (zend_get_parameters_ex(1, &function_name) != SUCCESS)) { WRONG_PARAM_COUNT; } if((*function_name)->type != IS_STRING) { zend_error(E_ERROR, "Function requires string argument"); } TSRMSLS_FETCH(); if(call_user_function_ex(CG(function_table), NULL, *function_name, &retval, 0, NULL, 0) != SUCCESS) { zend_error(E_ERROR, "Function call failed"); } zend_printf("We have %i as type\n", retval->type); *return_value = *retval; zval_copy_ctor(return_value); zval_ptr_dtor(&retval);</pre> </div> </div> </div> <p class="para"/> <div class="example-contents"> <div class="ccode"><pre class="ccode"><?php dl("call_userland.so"); function test_function() { echo "We are in the test function!\n"; return 'hello'; } $return_value = call_userland("test_function"); echo "Return value: '$return_value'"; ?></pre> </div> </div> <p class="para">The above example will output:</p> <div class="example-contents screen"> <div class="cdata"><pre> We are in the test function! We have 3 as type Return value: 'hello' </pre></div> </div> </div> <div class="sect2" id="internals2.ze1.zendapi.ini-file-support"> <h3 class="title">Initialization File Support</h3> <p class="para"> PHP 4 features a redesigned initialization file support. It's now possible to specify default initialization entries directly in your code, read and change these values at runtime, and create message handlers for change notifications. </p> <p class="para"> To create an .ini section in your own module, use the macros <em>PHP_INI_BEGIN()</em> to mark the beginning of such a section and <em>PHP_INI_END()</em> to mark its end. In between you can use <em>PHP_INI_ENTRY()</em> to create entries. <div class="example-contents"> <div class="ccode"><pre class="ccode">PHP_INI_BEGIN() PHP_INI_ENTRY("first_ini_entry", "has_string_value", PHP_INI_ALL, NULL) PHP_INI_ENTRY("second_ini_entry", "2", PHP_INI_SYSTEM, OnChangeSecond) PHP_INI_ENTRY("third_ini_entry", "xyz", PHP_INI_USER, NULL) PHP_INI_END()</pre> </div> </div> The <em>PHP_INI_ENTRY()</em> macro accepts four parameters: the entry name, the entry value, its change permissions, and a pointer to a change-notification handler. Both entry name and value must be specified as strings, regardless of whether they really are strings or integers. </p> <p class="para"> The permissions are grouped into three sections:<em>PHP_INI_SYSTEM</em> allows a change only directly in the <var class="filename">php.ini</var> file; <em>PHP_INI_USER</em> allows a change to be overridden by a user at runtime using additional configuration files, such as <var class="filename">.htaccess</var>; and <em>PHP_INI_ALL</em> allows changes to be made without restrictions. There's also a fourth level, <em>PHP_INI_PERDIR</em>, for which we couldn't verify its behavior yet. </p> <p class="para"> The fourth parameter consists of a pointer to a change-notification handler. Whenever one of these initialization entries is changed, this handler is called. Such a handler can be declared using the <em>PHP_INI_MH</em> macro: <div class="example-contents"> <div class="ccode"><pre class="ccode">PHP_INI_MH(OnChangeSecond); // handler for ini-entry "second_ini_entry" // specify ini-entries here PHP_INI_MH(OnChangeSecond) { zend_printf("Message caught, our ini entry has been changed to %s&lt;br&gt;", new_value); return(SUCCESS); }</pre> </div> </div> The new value is given to the change handler as string in the variable <span class="envar">new_value</span>. When looking at the definition of <em>PHP_INI_MH</em>, you actually have a few parameters to use: <div class="example-contents"> <div class="ccode"><pre class="ccode">#define PHP_INI_MH(name) int name(php_ini_entry *entry, char *new_value, uint new_value_length, void *mh_arg1, void *mh_arg2, void *mh_arg3)</pre> </div> </div> All these definitions can be found in <var class="filename">php_ini.h</var>. Your message handler will have access to a structure that contains the full entry, the new value, its length, and three optional arguments. These optional arguments can be specified with the additional macros <em>PHP_INI_ENTRY1</em> (allowing one additional argument), <em>PHP_INI_ENTRY2</em> (allowing two additional arguments), and <em>PHP_INI_ENTRY3</em> (allowing three additional arguments). </p> <p class="para"> The change-notification handlers should be used to cache initialization entries locally for faster access or to perform certain tasks that are required if a value changes. For example, if a constant connection to a certain host is required by a module and someone changes the hostname, automatically terminate the old connection and attempt a new one. </p> <p class="para"> Access to initialization entries can also be handled with the macros shown in <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.table.ini-macros" class="xref">Macros to Access Initialization Entries in PHP</a>. </p> <table id="internals2.ze1.zendapi.table.ini-macros" class="doctable table"> <caption><strong>Macros to Access Initialization Entries in PHP</strong></caption> <col style="width: 1.00*;" /> <col style="width: 1.66*;" /> <tbody class="tbody"> <tr> <td>Macro</td> <td>Description</td> </tr> <tr> <td><em>INI_INT(name)</em></td> <td>Returns the current value of entry <em>name</em> as integer (long).</td> </tr> <tr> <td><em>INI_FLT(name)</em></td> <td>Returns the current value of entry <em>name</em> as float (double).</td> </tr> <tr> <td><em>INI_STR(name)</em></td> <td>Returns the current value of entry <em>name</em> as string. <em class="emphasis">Note:</em> This string is not duplicated, but instead points to internal data. Further access requires duplication to local memory.</td> </tr> <tr> <td><em>INI_BOOL(name)</em></td> <td>Returns the current value of entry <em>name</em> as Boolean (defined as <span class="envar">zend_bool</span>, which currently means <span class="envar">unsigned char</span>).</td> </tr> <tr> <td><em>INI_ORIG_INT(name)</em></td> <td>Returns the original value of entry <em>name</em> as integer (long).</td> </tr> <tr> <td><em>INI_ORIG_FLT(name)</em></td> <td>Returns the original value of entry <em>name</em> as float (double).</td> </tr> <tr> <td><em>INI_ORIG_STR(name)</em></td> <td>Returns the original value of entry <em>name</em> as string. Note: This string is not duplicated, but instead points to internal data. Further access requires duplication to local memory.</td> </tr> <tr> <td><em>INI_ORIG_BOOL(name)</em></td> <td>Returns the original value of entry <em>name</em> as Boolean (defined as <span class="envar">zend_bool</span>, which currently means <span class="envar">unsigned char</span>).</td> </tr> </tbody> </table> <p class="para"> Finally, you have to introduce your initialization entries to PHP. This can be done in the module startup and shutdown functions, using the macros <em>REGISTER_INI_ENTRIES()</em> and <em>UNREGISTER_INI_ENTRIES()</em>: <div class="example-contents"> <div class="ccode"><pre class="ccode">ZEND_MINIT_FUNCTION(mymodule) { REGISTER_INI_ENTRIES(); } ZEND_MSHUTDOWN_FUNCTION(mymodule) { UNREGISTER_INI_ENTRIES(); }</pre> </div> </div> </p> </div> <div class="sect2" id="internals2.ze1.zendapi.where-to-go"> <h3 class="title">Where to Go from Here</h3> <p class="para"> You've learned a lot about PHP. You now know how to create dynamic loadable modules and statically linked extensions. You've learned how PHP and Zend deal with internal storage of variables and how you can create and access these variables. You know quite a set of tool functions that do a lot of routine tasks such as printing informational texts, automatically introducing variables to the symbol table, and so on. </p> <p class="para"> Even though this chapter often had a mostly "referential" character, we hope that it gave you insight on how to start writing your own extensions. For the sake of space, we had to leave out a lot; we suggest that you take the time to study the header files and some modules (especially the ones in the <var class="filename">ext/standard</var> directory and the MySQL module, as these implement commonly known functionality). This will give you an idea of how other people have used the API functions - particularly those that didn't make it into this chapter. </p> </div> <div class="sect2" id="internals2.ze1.zendapi.configuration-macros"> <h3 class="title">Reference: Some Configuration Macros</h3> <div class="sect3" id="internals2.ze1.zendapi.configuration-macros.config-m4"> <h4 class="title"><var class="filename">config.m4</var></h4> <p class="para"> The file <var class="filename">config.m4</var> is processed by <var class="filename">buildconf</var> and must contain all the instructions to be executed during configuration. For example, these can include tests for required external files, such as header files, libraries, and so on. PHP defines a set of macros that can be used in this process, the most useful of which are described in <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.tab.m4-macros" class="xref">M4 Macros for config.m4</a>. </p> <table id="internals2.ze1.zendapi.tab.m4-macros" class="doctable table"> <caption><strong>M4 Macros for <var class="filename">config.m4</var></strong></caption> <col style="width: 1.63*;" /> <col style="width: 1.00*;" /> <tbody class="tbody"> <tr> <td>Macro</td> <td>Description</td> </tr> <tr> <td><em>AC_MSG_CHECKING(message)</em></td> <td>Prints a "checking <message>" text during <var class="filename">configure</var>.</td> </tr> <tr> <td><em>AC_MSG_RESULT(value)</em></td> <td>Gives the result to <em>AC_MSG_CHECKING</em>; should specify either <em>yes</em> or <em>no</em> as <span class="envar">value</span>.</td> </tr> <tr> <td><em>AC_MSG_ERROR(message)</em></td> <td>Prints <span class="envar">message</span> as error message during <var class="filename">configure</var> and aborts the script.</td> </tr> <tr> <td><em>AC_DEFINE(name,value,description)</em></td> <td>Adds <em>#define</em> to <var class="filename">php_config.h</var> with the value of <span class="envar">value</span> and a comment that says <span class="envar">description</span> (this is useful for conditional compilation of your module).</td> </tr> <tr> <td><em>AC_ADD_INCLUDE(path)</em></td> <td>Adds a compiler include path; for example, used if the module needs to add search paths for header files.</td> </tr> <tr> <td><em>AC_ADD_LIBRARY_WITH_PATH(libraryname,librarypath)</em></td> <td>Specifies an additional library to link.</td> </tr> <tr> <td><em>AC_ARG_WITH(modulename,description,unconditionaltest,conditionaltest)</em></td> <td>Quite a powerful macro, adding the module with <span class="envar">description</span> to the <var class="filename">configure --help</var> output. PHP checks whether the option <em>--with-<modulename></em> is given to the <var class="filename">configure</var> script. If so, it runs the script <em>unconditionaltest</em> (for example, <em>--with-myext=yes</em>), in which case the value of the option is contained in the variable <span class="envar">$withval</span>. Otherwise, it executes <em>conditionaltest</em>. </td> </tr> <tr> <td><em>PHP_EXTENSION(modulename, [shared])</em></td> <td>This macro is a <em class="emphasis">must</em> to call for PHP to configure your extension. You can supply a second argument in addition to your module name, indicating whether you intend compilation as a shared module. This will result in a definition at compile time for your source as <em>COMPILE_DL_<modulename></em>.</td> </tr> </tbody> </table> </div> </div> <div class="sect2" id="internals2.ze1.zendapi.api-macros"> <h3 class="title">API Macros</h3> <p class="para">A set of macros was introduced into Zend's API that simplify access to <span class="envar">zval</span> containers (see <a href="internals2.ze1.zendapi.html#internals2.ze1.zendapi.tab.api-macros" class="xref">API Macros for Accessing zval Containers</a>).</p> <table id="internals2.ze1.zendapi.tab.api-macros" class="doctable table"> <caption><strong>API Macros for Accessing <span class="envar">zval</span> Containers</strong></caption> <col style="width: *;" /> <col style="width: *;" /> <tbody class="tbody"> <tr> <td>Macro</td> <td>Refers to</td> </tr> <tr> <td><em>Z_LVAL(zval)</em></td> <td><span class="envar">(zval).value.lval</span></td> </tr> <tr> <td><em>Z_DVAL(zval)</em></td> <td><span class="envar">(zval).value.dval</span></td> </tr> <tr> <td><em>Z_STRVAL(zval)</em></td> <td><span class="envar">(zval).value.str.val</span></td> </tr> <tr> <td><em>Z_STRLEN(zval)</em></td> <td><span class="envar">(zval).value.str.len</span></td> </tr> <tr> <td><em>Z_ARRVAL(zval)</em></td> <td><span class="envar">(zval).value.ht</span></td> </tr> <tr> <td><em>Z_LVAL_P(zval)</em></td> <td><span class="envar">(*zval).value.lval</span></td> </tr> <tr> <td><em>Z_DVAL_P(zval)</em></td> <td><span class="envar">(*zval).value.dval</span></td> </tr> <tr> <td><em>Z_STRVAL_P(zval_p)</em></td> <td><span class="envar">(*zval).value.str.val</span></td> </tr> <tr> <td><em>Z_STRLEN_P(zval_p)</em></td> <td><span class="envar">(*zval).value.str.len</span></td> </tr> <tr> <td><em>Z_ARRVAL_P(zval_p)</em></td> <td><span class="envar">(*zval).value.ht</span></td> </tr> <tr> <td><em>Z_LVAL_PP(zval_pp)</em></td> <td><span class="envar">(**zval).value.lval</span></td> </tr> <tr> <td><em>Z_DVAL_PP(zval_pp)</em></td> <td><span class="envar">(**zval).value.dval</span></td> </tr> <tr> <td><em>Z_STRVAL_PP(zval_pp)</em></td> <td><span class="envar">(**zval).value.str.val</span></td> </tr> <tr> <td><em>Z_STRLEN_PP(zval_pp)</em></td> <td><span class="envar">(**zval).value.str.len</span></td> </tr> <tr> <td><em>Z_ARRVAL_PP(zval_pp)</em></td> <td><span class="envar">(**zval).value.ht</span></td> </tr> </tbody> </table> </div> </div><hr /><div class="manualnavbar" style="text-align: center;"> <div class="prev" style="text-align: left; float: left;"><a href="internals2.ze1.streams.html">Streams API for PHP Extension Authors</a></div> <div class="next" style="text-align: right; float: right;"><a href="internals2.ze1.tsrm.html">TSRM API</a></div> <div class="up"><a href="internals2.ze1.html">Zend Engine 1</a></div> <div class="home"><a href="index.html">PHP Manual</a></div> </div></body></html>