cvs: phpdoc / Makefile.in configure.in manual.xml.in /en bookinfo.xml language-defs.ent /en/appendices phpdevel.xml /en/chapters streams.common.xml
streams.constants.xml streams.dir.xml streams.file.xml streams.socket.xml streams.structs.xml streams.xml /en/internals extendphp3.xml intro.xml
/en/internals/streams common.xml constants.xml dir.xml file.xml index.xml socket.xml structs.xml /en/internals/zendapi api-macros.xml arguments.xml
build.xml calling-user-functions.xml configuration-macros.xml copy-constructor.xml creating.xml index.xml ini-file-support.xml intro.xml layout.xml
overview.xml possibilities.xml printing.xml returning.xml startup-and-shutdown.xml structure.xml troubleshooting.xml using.xml variables.xml
where-to-go.xml /en/internals/zendapi/figures zend.01-internal-structure.png zend.02-first-module-output.png zend.03-wrong-parameter-count.png
zend.04-cross-converter.png zend.05-reference-test.png zend.06-variable-creation.png zend.07-warning-messages.png zend.08-phpinfo-output.png
zend.09-execution-info.png zend.10-userland.png /scripts file-entities.php.in missing-entities.php.in

From: Date: Sun, 21 Aug 2005 16:27:09 +0000
Subject: cvs: phpdoc / Makefile.in configure.in manual.xml.in /en bookinfo.xml language-defs.ent /en/appendices phpdevel.xml /en/chapters streams.common.xml
streams.constants.xml streams.dir.xml streams.file.xml streams.socket.xml streams.structs.xml streams.xml /en/internals extendphp3.xml intro.xml
/en/internals/streams common.xml constants.xml dir.xml file.xml index.xml socket.xml structs.xml /en/internals/zendapi api-macros.xml arguments.xml
build.xml calling-user-functions.xml configuration-macros.xml copy-constructor.xml creating.xml index.xml ini-file-support.xml intro.xml layout.xml
overview.xml possibilities.xml printing.xml returning.xml startup-and-shutdown.xml structure.xml troubleshooting.xml using.xml variables.xml
where-to-go.xml /en/internals/zendapi/figures zend.01-internal-structure.png zend.02-first-module-output.png zend.03-wrong-parameter-count.png
zend.04-cross-converter.png zend.05-reference-test.png zend.06-variable-creation.png zend.07-warning-messages.png zend.08-phpinfo-output.png
zend.09-execution-info.png zend.10-userland.png /scripts file-entities.php.in missing-entities.php.in
Groups: php.doc 
Request: Send a blank email to phpdoc+get-969369674@lists.php.net to get a copy of this message
goba Sun Aug 21 12:27:09 2005 EDT Added files: /phpdoc/en/internals extendphp3.xml intro.xml /phpdoc/en/internals/streams common.xml constants.xml dir.xml file.xml index.xml socket.xml structs.xml /phpdoc/en/internals/zendapi api-macros.xml arguments.xml build.xml calling-user-functions.xml configuration-macros.xml copy-constructor.xml creating.xml index.xml ini-file-support.xml intro.xml layout.xml overview.xml possibilities.xml printing.xml returning.xml startup-and-shutdown.xml structure.xml troubleshooting.xml using.xml variables.xml where-to-go.xml /phpdoc/en/internals/zendapi/figures zend.01-internal-structure.png zend.02-first-module-output.png zend.03-wrong-parameter-count.png zend.04-cross-converter.png zend.05-reference-test.png zend.06-variable-creation.png zend.07-warning-messages.png zend.08-phpinfo-output.png zend.09-execution-info.png zend.10-userland.png Removed files: /phpdoc/en/appendices phpdevel.xml /phpdoc/en/chapters streams.common.xml streams.constants.xml streams.dir.xml streams.file.xml streams.socket.xml streams.structs.xml streams.xml Modified files: /phpdoc Makefile.in configure.in manual.xml.in /phpdoc/en bookinfo.xml language-defs.ent /phpdoc/scripts file-entities.php.in missing-entities.php.in Log: New internals documentation section added: - PHP 3 development appendix moved to this part - Streams API docs moved to this part - ZendAPI docs with figures integrated in this part More info: http://news.php.net/php.doc/969369673

http://cvs.php.net/diff.php/phpdoc/Makefile.in?r1=1.168&r2=1.169&ty=u Index: phpdoc/Makefile.in diff -u phpdoc/Makefile.in:1.168 phpdoc/Makefile.in:1.169 --- phpdoc/Makefile.in:1.168 Sun Jul 10 13:34:59 2005 +++ phpdoc/Makefile.in Sun Aug 21 12:27:02 2005 @@ -16,7 +16,7 @@ # # -# $Id: Makefile.in,v 1.168 2005/07/10 17:34:59 nlopess Exp $ +# $Id: Makefile.in,v 1.169 2005/08/21 16:27:02 goba Exp $ # all: html @@ -82,17 +82,19 @@ touch .manual.xml zendapi: - @ZEND_FIGURES@ + cp $(srcdir)/en/internals/zendapi/figures/*.png . zendapihtml: - rm -rf html && mkdir html - @if test "@FIGURES@" != ""; then mkdir html/@FIGURES@ ; fi - @ZEND_FIGURES_HTML@ + rm -rf html && mkdir html && mkdir html/figures + cp $(srcdir)/en/internals/zendapi/figures/*.png ./html/figures zendapiphp: - rm -rf php && mkdir php - @if test "@FIGURES@" != ""; then mkdir php/@FIGURES@ ; fi - @ZEND_FIGURES_PHP@ + rm -rf php && mkdir php && mkdir php/figures + cp $(srcdir)/en/internals/zendapi/figures/*.png ./php/figures + +zendapihtmlhelp: + rm -rf ./htmlhelp/html && mkdir ./htmlhelp/html && mkdir htmlhelp/html/figures + cp $(srcdir)/en/internals/zendapi/figures/*.png ./htmlhelp/html/figures html: html/index.html bightml: @MANUAL@.html @@ -204,12 +206,7 @@ rm -rf ./howto/html && mkdir ./howto/html ${XSLTPROC} $(HOWTO_XSL_SHEET) ./howto/howto.xml -chm_xsl: manual.xml - rm -rf ./htmlhelp/html && mkdir ./htmlhelp/html - @if test "@FIGURES@" != ""; then \ - mkdir ./htmlhelp/html/@FIGURES@ ;\ - @ZEND_FIGURES@/htmlhelp/html/@FIGURES@ ;\ - fi +chm_xsl: manual.xml zendapihtmlhelp ${XSLTPROC} $(CHM_XSL_SHEET) manual.xml phpweb_xsl: manual.xml zendapiphp http://cvs.php.net/diff.php/phpdoc/configure.in?r1=1.230&r2=1.231&ty=u Index: phpdoc/configure.in diff -u phpdoc/configure.in:1.230 phpdoc/configure.in:1.231 --- phpdoc/configure.in:1.230 Sun Jul 17 13:01:41 2005 +++ phpdoc/configure.in Sun Aug 21 12:27:03 2005 @@ -1,4 +1,4 @@ -dnl $Id: configure.in,v 1.230 2005/07/17 17:01:41 nlopess Exp $ +dnl $Id: configure.in,v 1.231 2005/08/21 16:27:03 goba Exp $ dnl autoconf initialisation AC_INIT() @@ -491,51 +491,6 @@ dnl }}} AC_SUBST(EXT_SOURCE) -dnl {{{ check for ZendEngine API documentation to include - -AC_MSG_CHECKING(for ZendAPI) - -ZENDAPI="not found" -AC_ARG_WITH(zendapi, -[ --with-zendapi=[DIR] look for ZendAPI documentation in the specified directory], -[ - if test -f "$withval/Extending_Zend.xml" ; then - ZENDAPI=$withval - fi -],[ - for dir in \ - $srcdir/en/ZendAPI \ - $srcdir/ZendAPI \ - $srcdir/../ZendAPI - do - if test -f "$dir/Extending_Zend.xml"; then - ZENDAPI="$dir" - break - fi - done -]) - -if test -d "$ZENDAPI"; then - FIGURES="figures" - ZEND_FIGURES="cp $ZENDAPI/figures/*.png ." - ZEND_FIGURES_HTML="$ZEND_FIGURES/html/$FIGURES" - ZEND_FIGURES_PHP="$ZEND_FIGURES/php/$FIGURES" -else - FIGURES="" - ZEND_FIGURES="" - ZEND_FIGURES_HTML="" - ZEND_FIGURES_PHP="" -fi - -AC_MSG_RESULT($ZENDAPI) -AC_SUBST(ZENDAPI) -AC_SUBST(ZEND_FIGURES) -AC_SUBST(ZEND_FIGURES_HTML) -AC_SUBST(ZEND_FIGURES_PHP) -AC_SUBST(FIGURES) - -dnl }}} - dnl {{{ AC_MSG_CHECKING(for CSS to use for html docs) AC_ARG_WITH(htmlcss, http://cvs.php.net/diff.php/phpdoc/manual.xml.in?r1=1.207&r2=1.208&ty=u Index: phpdoc/manual.xml.in diff -u phpdoc/manual.xml.in:1.207 phpdoc/manual.xml.in:1.208 --- phpdoc/manual.xml.in:1.207 Sun Aug 21 08:38:04 2005 +++ phpdoc/manual.xml.in Sun Aug 21 12:27:03 2005 @@ -2,7 +2,7 @@ <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN" "@srcdir@/dtds/dbxml-4.1.2/docbookx.dtd" [ -<!-- $Revision: 1.207 $ --> +<!-- $Revision: 1.208 $ --> <!-- Add translated specific definitions and snippets --> <!ENTITY % language-defs SYSTEM "@srcdir@/@LANGDIR@/language-defs.ent"> @@ -122,11 +122,12 @@ &addon.extensions; - &zendapi.toc; - <part id="api"> - <title>&api;</title> - <titleabbrev>&apiabbrev;</titleabbrev> - &chapters.streams; + <part id="internals"> + <title>&Internals;</title> + &internals.intro; + &internals.extendphp3; + &internals.streams.index; + &internals.zendapi.index; </part> <part id="faq"> @@ -155,7 +156,6 @@ &appendices.migration4; &appendices.migration; &appendices.debugger; - &appendices.phpdevel; &appendices.configure.index; &appendices.ini; &appendices.extensions; http://cvs.php.net/diff.php/phpdoc/en/bookinfo.xml?r1=1.44&r2=1.45&ty=u Index: phpdoc/en/bookinfo.xml diff -u phpdoc/en/bookinfo.xml:1.44 phpdoc/en/bookinfo.xml:1.45 --- phpdoc/en/bookinfo.xml:1.44 Fri Dec 31 20:35:54 2004 +++ phpdoc/en/bookinfo.xml Sun Aug 21 12:27:04 2005 @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="iso-8859-1"?> -<!-- $Revision: 1.44 $ --> +<!-- $Revision: 1.45 $ --> <bookinfo id="bookinfo"> <title>&PHPManual;</title> @@ -40,11 +40,8 @@ Note that this address is mapped to a publicly archived mailing list. </simpara> <simpara> - The 'Extending PHP 4.0' section of this manual is copyright &copy; 2000 by - Zend Technologies, Ltd. This material may be distributed only subject to - the terms and conditions set forth in the Open Publication License, v1.0 - or later (the latest version is presently available at - <ulink url="&url.opl;">&url.opl;</ulink>). + The <xref linkend="zend"/> section of the documentation is based on an + initial contribution by Zend Technologies. </simpara> </legalnotice> http://cvs.php.net/diff.php/phpdoc/en/language-defs.ent?r1=1.27&r2=1.28&ty=u Index: phpdoc/en/language-defs.ent diff -u phpdoc/en/language-defs.ent:1.27 phpdoc/en/language-defs.ent:1.28 --- phpdoc/en/language-defs.ent:1.27 Sun Apr 24 20:29:37 2005 +++ phpdoc/en/language-defs.ent Sun Aug 21 12:27:04 2005 @@ -1,4 +1,4 @@ -<!-- $Revision: 1.27 $ --> +<!-- $Revision: 1.28 $ --> <!-- Part titles used mostly in manual.xml itself --> <!ENTITY PHPManual "PHP Manual"> @@ -16,8 +16,8 @@ <!ENTITY PEAR "PEAR: the PHP Extension and Application Repository"> <!ENTITY FAQ "FAQ: Frequently Asked Questions"> <!ENTITY FAQabbrev "FAQ"> -<!ENTITY api "PHP API: Interfaces for extension writers"> -<!ENTITY apiabbrev "PHP API"> +<!ENTITY Internals "PHP and Zend Engine Internals"> +<!ENTITY ZendAPI "Zend API: Hacking the Core of PHP"> <!ENTITY FunctionIndex "Function Index"> <!ENTITY CHMEdition "HTML Help Edition"> <!ENTITY ReservedConstants "Predefined Constants"> @@ -52,4 +52,4 @@ <!ENTITY reftitle.runtime '<title>Runtime Configuration</title>'> <!ENTITY reftitle.returnvalues '<title>Return Values</title>'> <!ENTITY reftitle.seealso '<title>See Also</title>'> -<!ENTITY reftitle.notes '<title>Notes</title>'> \ No newline at end of file +<!ENTITY reftitle.notes '<title>Notes</title>'> http://cvs.php.net/diff.php/phpdoc/scripts/file-entities.php.in?r1=1.38&r2=1.39&ty=u Index: phpdoc/scripts/file-entities.php.in diff -u phpdoc/scripts/file-entities.php.in:1.38 phpdoc/scripts/file-entities.php.in:1.39 --- phpdoc/scripts/file-entities.php.in:1.38 Thu Aug 11 22:03:50 2005 +++ phpdoc/scripts/file-entities.php.in Sun Aug 21 12:27:08 2005 @@ -17,7 +17,7 @@ | Gabor Hojtsy <goba@php.net> | +----------------------------------------------------------------------+ - $Id: file-entities.php.in,v 1.38 2005/08/12 02:03:50 dbs Exp $ + $Id: file-entities.php.in,v 1.39 2005/08/21 16:27:08 goba Exp $ */ /** @@ -25,7 +25,6 @@ * Create phpdoc/entities/file-entities.ent with respect * to all the specialities needed: * - * . ZendAPI integration * . CHM only appendix integration * . Special install part (temporary) * . Reserved constant part (temporary) @@ -47,9 +46,6 @@ // ......:ARGUMENT PARSING:..................................................... -// Zend API integration info (either a path or "not found") -$zendapi = ("@ZENDAPI@" == "not found" ? FALSE : "@ZENDAPI@"); - $not_windows = !eregi('WIN',PHP_OS); // The dir for PHP. If the cygwin wasn't compiled on Cygwin, the path needs to be stripped. @@ -162,29 +158,6 @@ // File header fputs($fp, "<!-- DON'T TOUCH - AUTOGENERATED BY file-entities.php -->\n\n"); -// ZendAPI integration -if ($zendapi !== FALSE) { - - // Use absolute path to ZendAPI docs - $zendapi = abs_path($zendapi); - - fputs( - $fp, - "<!-- begin ZendAPI integration -->\n" . - entstr("% zend.defs", "$zendapi/Extending_Zend.ent") . - entstr("zendapi.toc", "$zendapi/Extending_Zend.xml") . - "%zend.defs;\n<!-- end ZendAPI integration -->\n\n" - ); - echo " Zend part included\n"; -} else { - fputs( - $fp, - "<!-- ZendAPI not found -->\n" . - entstr("zendapi.toc", "") . "\n" - ); - echo " Zend part (ZendAPI) not found. (Don't worry about this)\n"; -} - // The global function index page is special fputs( $fp, http://cvs.php.net/diff.php/phpdoc/scripts/missing-entities.php.in?r1=1.18&r2=1.19&ty=u Index: phpdoc/scripts/missing-entities.php.in diff -u phpdoc/scripts/missing-entities.php.in:1.18 phpdoc/scripts/missing-entities.php.in:1.19 --- phpdoc/scripts/missing-entities.php.in:1.18 Mon Aug 1 07:00:27 2005 +++ phpdoc/scripts/missing-entities.php.in Sun Aug 21 12:27:08 2005 @@ -17,7 +17,7 @@ | Gabor Hojtsy <goba@php.net> | +----------------------------------------------------------------------+ - $Id: missing-entities.php.in,v 1.18 2005/08/01 11:00:27 nlopess Exp $ + $Id: missing-entities.php.in,v 1.19 2005/08/21 16:27:08 goba Exp $ */ set_time_limit(0); @@ -139,14 +139,7 @@ echo "\nCreated file: @LANGDIR@/missing-ids.xml\n"; if (!empty($missing_ids)) { foreach ($missing_ids as $k => $v) { - if (false !== strpos('<para id="zend"', $v)) { - echo "* " . preg_replace('@[\s]+@', ' ', $v) . "\n"; - } else { - echo "* Zend id is missing. (Don't worry about this)\n"; - if (count($missing_ids) === 1) { - echo "* No other missing ids were found\n"; - } - } + echo "* " . preg_replace('@[\s]+@', ' ', $v) . "\n"; } } else { echo "* No missing ids found\n"; http://cvs.php.net/co.php/phpdoc/en/internals/extendphp3.xml?r=1.1&p=1 Index: phpdoc/en/internals/extendphp3.xml +++ phpdoc/en/internals/extendphp3.xml <?xml version="1.0" encoding="iso-8859-1"?> <!-- $Revision: 1.1 $ --> <chapter id="phpdevel"> <title>Extending PHP 3</title> <simpara> This section is rather outdated and demonstrates how to extend PHP 3. If you're interested in PHP 4, please read the section on the <link linkend="zend">Zend API</link>. </simpara> <sect1 id="phpdevel-addfunc"> <title>Adding functions to PHP</title> <sect2 id="phpdevel-addfunc-prototype"> <title>Function Prototype</title> <para> All functions look like this: <programlisting role="c"> <![CDATA[ void php3_foo(INTERNAL_FUNCTION_PARAMETERS) { } ]]> </programlisting> Even if your function doesn't take any arguments, this is how it is called.</para></sect2> <sect2 id="phpdevel-addfunc-args"> <title>Function Arguments</title> <para> Arguments are always of type pval. This type contains a union which has the actual type of the argument. So, if your function takes two arguments, you would do something like the following at the top of your function:</para> <para> <example> <title>Fetching function arguments</title> <programlisting role="c"> <![CDATA[ pval *arg1, *arg2; if (ARG_COUNT(ht) != 2 || getParameters(ht,2,&arg1,&arg2)==FAILURE) { WRONG_PARAM_COUNT; } ]]> </programlisting> </example> NOTE: Arguments can be passed either by value or by reference. In both cases you will need to pass &amp;(pval *) to getParameters. If you want to check if the n'th parameter was sent to you by reference or not, you can use the function, ParameterPassedByReference(ht,n). It will return either 1 or 0.</para> <simpara> When you change any of the passed parameters, whether they are sent by reference or by value, you can either start over with the parameter by calling pval_destructor on it, or if it's an ARRAY you want to add to, you can use functions similar to the ones in internal_functions.h which manipulate return_value as an ARRAY. </simpara> <simpara> Also if you change a parameter to IS_STRING make sure you first assign the new estrdup()'ed string and the string length, and only later change the type to IS_STRING. If you change the string of a parameter which already IS_STRING or IS_ARRAY you should run pval_destructor on it first.</simpara></sect2> <sect2 id="phpdevel-addfunc-varargs"> <title>Variable Function Arguments</title> <para> A function can take a variable number of arguments. If your function can take either 2 or 3 arguments, use the following:</para> <para> <example> <title>Variable function arguments</title> <programlisting role="c"> <![CDATA[ pval *arg1, *arg2, *arg3; int arg_count = ARG_COUNT(ht); if (arg_count < 2 || arg_count > 3 || getParameters(ht,arg_count,&arg1,&arg2,&arg3)==FAILURE) { WRONG_PARAM_COUNT; } ]]> </programlisting> </example></para></sect2> <sect2 id="phpdevel-addfunc-using-args"> <title>Using the Function Arguments</title> <para> The type of each argument is stored in the pval type field. This type can be any of the following: <table> <title>PHP Internal Types</title> <tgroup cols="2"> <tbody> <row> <entry>IS_STRING</entry> <entry>String</entry> </row> <row> <entry>IS_DOUBLE</entry> <entry>Double-precision floating point</entry> </row> <row> <entry>IS_LONG</entry> <entry>Long integer</entry> </row> <row> <entry>IS_ARRAY</entry> <entry>Array</entry> </row> <row> <entry>IS_EMPTY</entry> <entry>None</entry> </row> <row> <entry>IS_USER_FUNCTION</entry> <entry>??</entry> </row> <row> <entry>IS_INTERNAL_FUNCTION</entry> <entry>?? (if some of these cannot be passed to a function - delete)</entry> </row> <row> <entry>IS_CLASS</entry> <entry>??</entry> </row> <row> <entry>IS_OBJECT</entry> <entry>??</entry> </row> </tbody> </tgroup> </table></para> <para> If you get an argument of one type and would like to use it as another, or if you just want to force the argument to be of a certain type, you can use one of the following conversion functions: <programlisting role="c"> <![CDATA[ convert_to_long(arg1); convert_to_double(arg1); convert_to_string(arg1); convert_to_boolean_long(arg1); /* If the string is "" or "0" it becomes 0, 1 otherwise */ convert_string_to_number(arg1); /* Converts string to either LONG or DOUBLE depending on string */ ]]> </programlisting></para> <simpara> These function all do in-place conversion. They do not return anything.</simpara> <para> The actual argument is stored in a union; the members are: <itemizedlist> <listitem><simpara>IS_STRING: arg1-&gt;value.str.val</simpara></listitem> <listitem><simpara>IS_LONG: arg1-&gt;value.lval</simpara></listitem> <listitem><simpara>IS_DOUBLE: arg1-&gt;value.dval</simpara></listitem> </itemizedlist></para></sect2> <sect2 id="phpdevel-addfunc-memmgmt"> <title>Memory Management in Functions</title> <simpara> Any memory needed by a function should be allocated with either emalloc() or estrdup(). These are memory handling abstraction functions that look and smell like the normal malloc() and strdup() functions. Memory should be freed with efree().</simpara> <simpara> There are two kinds of memory in this program: memory which is returned to the parser in a variable, and memory which you need for temporary storage in your internal function. When you assign a string to a variable which is returned to the parser you need to make sure you first allocate the memory with either emalloc() or estrdup(). This memory should NEVER be freed by you, unless you later in the same function overwrite your original assignment (this kind of programming practice is not good though).</simpara> <simpara> For any temporary/permanent memory you need in your functions/library you should use the three emalloc(), estrdup(), and efree() functions. They behave EXACTLY like their counterpart functions. Anything you emalloc() or estrdup() you have to efree() at some point or another, unless it's supposed to stick around until the end of the program; otherwise, there will be a memory leak. The meaning of "the functions behave exactly like their counterparts" is: if you efree() something which was not emalloc()'ed nor estrdup()'ed you might get a segmentation fault. So please take care and free all of your wasted memory.</simpara> <simpara> If you compile with "-DDEBUG", PHP will print out a list of all memory that was allocated using emalloc() and estrdup() but never freed with efree() when it is done running the specified script.</simpara></sect2> <sect2 id="phpdevel-addfunc-symtab"> <title>Setting Variables in the Symbol Table</title> <para> A number of macros are available which make it easier to set a variable in the symbol table: <itemizedlist> <listitem><simpara>SET_VAR_STRING(name,value)</simpara></listitem> <listitem><simpara>SET_VAR_DOUBLE(name,value)</simpara></listitem> <listitem><simpara>SET_VAR_LONG(name,value)</simpara></listitem> </itemizedlist> </para> <warning> <para> Be careful with SET_VAR_STRING. The value part must be malloc'ed manually because the memory management code will try to free this pointer later. Do not pass statically allocated memory into a SET_VAR_STRING. </para> </warning> <simpara> Symbol tables in PHP are implemented as hash tables. At any given time, &amp;symbol_table is a pointer to the 'main' symbol table, and active_symbol_table points to the currently active symbol table (these may be identical like in startup, or different, if you're inside a function).</simpara> <para> The following examples use 'active_symbol_table'. You should replace it with &amp;symbol_table if you specifically want to work with the 'main' symbol table. Also, the same functions may be applied to arrays, as explained below.</para> <para> <example> <title>Checking whether <varname>$foo</varname> exists in a symbol table</title> <programlisting role="c"> <![CDATA[ if (hash_exists(active_symbol_table,"foo",sizeof("foo"))) { exists... } else { doesn't exist } ]]> </programlisting> </example> <example> <title>Finding a variable's size in a symbol table</title> <programlisting role="c"> <![CDATA[ hash_find(active_symbol_table,"foo",sizeof("foo"),&pvalue); check(pvalue.type); ]]> </programlisting> </example> Arrays in PHP are implemented using the same hashtables as symbol tables. This means the two above functions can also be used to check variables inside arrays.</para> <simpara> If you want to define a new array in a symbol table, you should do the following.</simpara> <simpara> First, you may want to check whether it exists and abort appropriately, using hash_exists() or hash_find().</simpara> <simpara> Next, initialize the array:</simpara> <para> <example> <title>Initializing a new array</title> <programlisting role="c"> <![CDATA[ pval arr; if (array_init(&arr) == FAILURE) { failed... }; hash_update(active_symbol_table,"foo",sizeof("foo"),&arr,sizeof(pval),NULL); ]]> </programlisting> </example> This code declares a new array, named <varname>$foo</varname>, in the active symbol table. This array is empty.</para> <simpara> Here's how to add new entries to it:</simpara> <para> <example> <title>Adding entries to a new array</title> <programlisting role="c"> <![CDATA[ pval entry; entry.type = IS_LONG; entry.value.lval = 5; /* defines $foo["bar"] = 5 */ hash_update(arr.value.ht,"bar",sizeof("bar"),&entry,sizeof(pval),NULL); /* defines $foo[7] = 5 */ hash_index_update(arr.value.ht,7,&entry,sizeof(pval),NULL); /* defines the next free place in $foo[], * $foo[8], to be 5 (works like php2) */ hash_next_index_insert(arr.value.ht,&entry,sizeof(pval),NULL); ]]> </programlisting> </example> If you'd like to modify a value that you inserted to a hash, you must first retrieve it from the hash. To prevent that overhead, you can supply a pval ** to the hash add function, and it'll be updated with the pval * address of the inserted element inside the hash. If that value is &null; (like in all of the above examples) - that parameter is ignored.</para> <simpara> hash_next_index_insert() uses more or less the same logic as <literal>$foo[] = bar;</literal> in PHP 2.0.</simpara> <simpara> If you are building an array to return from a function, you can initialize the array just like above by doing:</simpara> <programlisting role="c"> <![CDATA[ if (array_init(return_value) == FAILURE) { failed...; } ]]> </programlisting> <simpara> ...and then adding values with the helper functions:</simpara> <programlisting role="c"> <![CDATA[ add_next_index_long(return_value,long_value); add_next_index_double(return_value,double_value); add_next_index_string(return_value,estrdup(string_value)); ]]> </programlisting> <para> Of course, if the adding isn't done right after the array initialization, you'd probably have to look for the array first: <programlisting role="c"> <![CDATA[ pval *arr; if (hash_find(active_symbol_table,"foo",sizeof("foo"),(void **)&arr)==FAILURE) { can't find... } else { use arr->value.ht... } ]]> </programlisting></para> <simpara> Note that hash_find receives a pointer to a pval pointer, and not a pval pointer.</simpara> <simpara> Just about any hash function returns SUCCESS or FAILURE (except for hash_exists(), which returns a boolean truth value).</simpara></sect2> <sect2 id="phpdevel-addfunc-retsimple"> <title>Returning simple values</title> <simpara> A number of macros are available to make returning values from a function easier.</simpara> <para> The RETURN_* macros all set the return value and return from the function: <itemizedlist> <listitem><simpara>RETURN</simpara></listitem> <listitem><simpara>RETURN_FALSE</simpara></listitem> <listitem><simpara>RETURN_TRUE</simpara></listitem> <listitem><simpara>RETURN_LONG(l)</simpara></listitem> <listitem><simpara>RETURN_STRING(s,dup) If dup is &true;, duplicates the string</simpara></listitem> <listitem><simpara>RETURN_STRINGL(s,l,dup) Return string (s) specifying length (l).</simpara></listitem> <listitem><simpara>RETURN_DOUBLE(d)</simpara></listitem> </itemizedlist></para> <para> The RETVAL_* macros set the return value, but do not return. <itemizedlist> <listitem><simpara>RETVAL_FALSE</simpara></listitem> <listitem><simpara>RETVAL_TRUE</simpara></listitem> <listitem><simpara>RETVAL_LONG(l)</simpara></listitem> <listitem><simpara>RETVAL_STRING(s,dup) If dup is &true;, duplicates the string</simpara></listitem> <listitem><simpara>RETVAL_STRINGL(s,l,dup) Return string (s) specifying length (l).</simpara></listitem> <listitem><simpara>RETVAL_DOUBLE(d)</simpara></listitem> </itemizedlist></para> <simpara> The string macros above will all estrdup() the passed 's' argument, so you can safely free the argument after calling the macro, or alternatively use statically allocated memory.</simpara> <simpara> If your function returns boolean success/error responses, always use RETURN_TRUE and RETURN_FALSE respectively.</simpara></sect2> <sect2 id="phpdevel-addfunc-retcomplex"> <title>Returning complex values</title> <simpara> Your function can also return a complex data type such as an object or an array.</simpara> <para> Returning an object: <orderedlist numeration="arabic"> <listitem><simpara>Call object_init(return_value).</simpara></listitem> <listitem><para>Fill it up with values. The functions available for this purpose are listed below.</para></listitem> <listitem><para> Possibly, register functions for this object. In order to obtain values from the object, the function would have to fetch "this" from the active_symbol_table. Its type should be IS_OBJECT, and it's basically a regular hash table (i.e., you can use regular hash functions on .value.ht). The actual registration of the function can be done using: <programlisting role="c"> <![CDATA[ add_method( return_value, function_name, function_ptr ); ]]> </programlisting> </para></listitem> </orderedlist></para> <para> The functions used to populate an object are: <itemizedlist> <listitem><simpara>add_property_long( return_value, property_name, l ) - Add a property named 'property_name', of type long, equal to 'l'</simpara></listitem> <listitem><simpara>add_property_double( return_value, property_name, d ) - Same, only adds a double</simpara></listitem> <listitem><simpara>add_property_string( return_value, property_name, str ) - Same, only adds a string</simpara></listitem> <listitem><simpara>add_property_stringl( return_value, property_name, str, l ) - Same, only adds a string of length 'l'</simpara></listitem> </itemizedlist></para> <para> Returning an array: <orderedlist numeration="arabic"> <listitem><simpara>Call array_init(return_value).</simpara></listitem> <listitem><simpara>Fill it up with values. The functions available for this purpose are listed below.</simpara></listitem> </orderedlist></para> <para> The functions used to populate an array are: <itemizedlist> <listitem><simpara>add_assoc_long(return_value,key,l) - add associative entry with key 'key' and long value 'l'</simpara></listitem> <listitem><simpara>add_assoc_double(return_value,key,d)</simpara></listitem> <listitem><simpara>add_assoc_string(return_value,key,str,duplicate)</simpara></listitem> <listitem><simpara>add_assoc_stringl(return_value,key,str,length,duplicate) specify the string length</simpara></listitem> <listitem><simpara>add_index_long(return_value,index,l) - add entry in index 'index' with long value 'l'</simpara></listitem> <listitem><simpara>add_index_double(return_value,index,d)</simpara></listitem> <listitem><simpara>add_index_string(return_value,index,str)</simpara></listitem> <listitem><simpara>add_index_stringl(return_value,index,str,length) - specify the string length</simpara></listitem> <listitem><simpara>add_next_index_long(return_value,l) - add an array entry in the next free offset with long value 'l'</simpara></listitem> <listitem><simpara>add_next_index_double(return_value,d)</simpara></listitem> <listitem><simpara>add_next_index_string(return_value,str)</simpara></listitem> <listitem><simpara>add_next_index_stringl(return_value,str,length) - specify the string length</simpara></listitem> </itemizedlist></para></sect2> <sect2 id="phpdevel-addfunc-reslist"> <title>Using the resource list</title> <simpara> PHP has a standard way of dealing with various types of resources. This replaces all of the local linked lists in PHP 2.0.</simpara> <para> Available functions: <itemizedlist> <listitem><simpara>php3_list_insert(ptr, type) - returns the 'id' of the newly inserted resource</simpara></listitem> <listitem><simpara>php3_list_delete(id) - delete the resource with the specified id</simpara></listitem> <listitem><simpara>php3_list_find(id,*type) - returns the pointer of the resource with the specified id, updates 'type' to the resource's type</simpara></listitem> </itemizedlist> Typically, these functions are used for SQL drivers but they can be used for anything else; for instance, maintaining file descriptors.</para> <simpara> Typical list code would look like this:</simpara> <para> <example> <title>Adding a new resource</title> <programlisting role="c"> <![CDATA[ RESOURCE *resource; /* ...allocate memory for resource and acquire resource... */ /* add a new resource to the list */ return_value->value.lval = php3_list_insert((void *) resource, LE_RESOURCE_TYPE); return_value->type = IS_LONG; ]]> </programlisting> </example> <example> <title>Using an existing resource</title> <programlisting role="c"> <![CDATA[ pval *resource_id; RESOURCE *resource; int type; convert_to_long(resource_id); resource = php3_list_find(resource_id->value.lval, &type); if (type != LE_RESOURCE_TYPE) { php3_error(E_WARNING,"resource index %d has the wrong type",resource_id->value.lval); RETURN_FALSE; } /* ...use resource... */ ]]> </programlisting> </example> <example> <title>Deleting an existing resource</title> <programlisting role="c"> <![CDATA[ pval *resource_id; RESOURCE *resource; int type; convert_to_long(resource_id); php3_list_delete(resource_id->value.lval); ]]> </programlisting> </example> The resource types should be registered in php3_list.h, in enum list_entry_type. In addition, one should add shutdown code for any new resource type defined, in list.c's list_entry_destructor() (even if you don't have anything to do on shutdown, you must add an empty case).</para></sect2> <sect2 id="phpdevel-addfunc-prestable"> <title>Using the persistent resource table</title> <para> PHP has a standard way of storing persistent resources (i.e., resources that are kept in between hits). The first module to use this feature was the MySQL module, and mSQL followed it, so one can get the general impression of how a persistent resource should be used by reading mysql.c. The functions you should look at are: <simplelist> <member>php3_mysql_do_connect</member> <member>php3_mysql_connect()</member> <member>php3_mysql_pconnect()</member> </simplelist></para> <para> The general idea of persistence modules is this: <orderedlist numeration="arabic"> <listitem><simpara>Code all of your module to work with the regular resource list mentioned in section (9).</simpara></listitem> <listitem><simpara>Code extra connect functions that check if the resource already exists in the persistent resource list. If it does, register it as in the regular resource list as a pointer to the persistent resource list (because of 1., the rest of the code should work immediately). If it doesn't, then create it, add it to the persistent resource list AND add a pointer to it from the regular resource list, so all of the code would work since it's in the regular resource list, but on the next connect, the resource would be found in the persistent resource list and be used without having to recreate it. You should register these resources with a different type (e.g. LE_MYSQL_LINK for non-persistent link and LE_MYSQL_PLINK for a persistent link).</simpara></listitem> </orderedlist></para> <simpara> If you read mysql.c, you'll notice that except for the more complex connect function, nothing in the rest of the module has to be changed.</simpara> <simpara> The very same interface exists for the regular resource list and the persistent resource list, only 'list' is replaced with 'plist':</simpara> <itemizedlist> <listitem><simpara>php3_plist_insert(ptr, type) - returns the 'id' of the newly inserted resource</simpara></listitem> <listitem><simpara>php3_plist_delete(id) - delete the resource with the specified id</simpara></listitem> <listitem><simpara>php3_plist_find(id,*type) - returns the pointer of the resource with the specified id, updates 'type' to the resource's type</simpara></listitem> </itemizedlist> <simpara> However, it's more than likely that these functions would prove to be useless for you when trying to implement a persistent module. Typically, one would want to use the fact that the persistent resource list is really a hash table. For instance, in the MySQL/mSQL modules, when there's a pconnect() call (persistent connect), the function builds a string out of the host/user/passwd that were passed to the function, and hashes the SQL link with this string as a key. The next time someone calls a pconnect() with the same host/user/passwd, the same key would be generated, and the function would find the SQL link in the persistent list.</simpara> <simpara> Until further documented, you should look at mysql.c or msql.c to see how one should use the plist's hash table abilities.</simpara> <simpara> One important thing to note: resources going into the persistent resource list must *NOT* be allocated with PHP's memory manager, i.e., they should NOT be created with emalloc(), estrdup(), etc. Rather, one should use the regular malloc(), strdup(), etc. The reason for this is simple - at the end of the request (end of the hit), every memory chunk that was allocated using PHP's memory manager is deleted. Since the persistent list isn't supposed to be erased at the end of a request, one mustn't use PHP's memory manager for allocating resources that go to it.</simpara> <simpara> When you register a resource that's going to be in the persistent list, you should add destructors to it both in the non-persistent list and in the persistent list. The destructor in the non-persistent list destructor shouldn't do anything. The one in the persistent list destructor should properly free any resources obtained by that type (e.g. memory, SQL links, etc). Just like with the non-persistent resources, you *MUST* add destructors for every resource, even it requires no destruction and the destructor would be empty. Remember, since emalloc() and friends aren't to be used in conjunction with the persistent list, you mustn't use efree() here either.</simpara></sect2> <sect2 id="phpdevel-addfunc-addcfg"> <title>Adding runtime configuration directives</title> <para> Many of the features of PHP can be configured at runtime. These configuration directives can appear in either the designated php3.ini file, or in the case of the Apache module version in the Apache .conf files. The advantage of having them in the Apache .conf files is that they can be configured on a per-directory basis. This means that one directory may have a certain safemodeexecdir for example, while another directory may have another. This configuration granularity is especially handy when a server supports multiple virtual hosts.</para> <para> The steps required to add a new directive: <orderedlist> <listitem><simpara>Add directive to php3_ini_structure struct in mod_php3.h.</simpara></listitem> <listitem><simpara>In main.c, edit the php3_module_startup function and add the appropriate cfg_get_string() or cfg_get_long() call.</simpara></listitem> <listitem><simpara>Add the directive, restrictions and a comment to the php3_commands structure in mod_php3.c. Note the restrictions part. RSRC_CONF are directives that can only be present in the actual Apache .conf files. Any OR_OPTIONS directives can be present anywhere, include normal &htaccess; files.</simpara></listitem> <listitem><simpara>In either php3take1handler() or php3flaghandler() add the appropriate entry for your directive.</simpara></listitem> <listitem><simpara>In the configuration section of the _php3_info() function in functions/info.c you need to add your new directive.</simpara></listitem> <listitem><simpara>And last, you of course have to use your new directive somewhere. It will be addressable as php3_ini.directive.</simpara></listitem> </orderedlist></para></sect2></sect1> <sect1 id="calling-user-functions"> <title>Calling User Functions</title> <simpara> To call user functions from an internal function, you should use the <function>call_user_function</function> function. </simpara> <simpara> <function>call_user_function</function> returns SUCCESS on success, and FAILURE in case the function cannot be found. You should check that return value! If it returns SUCCESS, you are responsible for destroying the retval pval yourself (or return it as the return value of your function). If it returns FAILURE, the value of retval is undefined, and you mustn't touch it. </simpara> <simpara> All internal functions that call user functions <emphasis>must</emphasis> be reentrant. Among other things, this means they must not use globals or static variables. </simpara> <simpara> <function>call_user_function</function> takes six arguments: </simpara> <sect2 id="calling-user-functions.function-table"> <title>HashTable *function_table</title> <simpara> This is the hash table in which the function is to be looked up. </simpara></sect2> <sect2 id="calling-user-functions.object"> <title>pval *object</title> <simpara> This is a pointer to an object on which the function is invoked. This should be &null; if a global function is called. If it's not &null; (i.e. it points to an object), the function_table argument is ignored, and instead taken from the object's hash. The object *may* be modified by the function that is invoked on it (that function will have access to it via $this). If for some reason you don't want that to happen, send a copy of the object instead. </simpara></sect2> <sect2 id="calling-user-functions.function-name"> <title>pval *function_name</title> <simpara> The name of the function to call. Must be a pval of type IS_STRING with function_name.str.val and function_name.str.len set to the appropriate values. The function_name is modified by call_user_function() - it's converted to lowercase. If you need to preserve the case, send a copy of the function name instead. </simpara></sect2> <sect2 id="calling-user-functions.retval"> <title>pval *retval</title> <simpara> A pointer to a pval structure, into which the return value of the invoked function is saved. The structure must be previously allocated - <function>call_user_function</function> does NOT allocate it by itself. </simpara></sect2> <sect2 id="calling-user-functions.param-count"> <title>int param_count</title> <simpara> The number of parameters being passed to the function. </simpara></sect2> <sect2 id="calling-user-functions.params"> <title>pval *params[]</title> <simpara> An array of pointers to values that will be passed as arguments to the function, the first argument being in offset 0, the second in offset 1, etc. The array is an array of pointers to pval's; The pointers are sent as-is to the function, which means if the function modifies its arguments, the original values are changed (passing by reference). If you don't want that behavior, pass a copy instead. </simpara></sect2></sect1> <sect1 id="phpdevel-errors"> <title>Reporting Errors</title> <simpara> To report errors from an internal function, you should call the <function>php3_error</function> function. This takes at least two parameters -- the first is the level of the error, the second is the format string for the error message (as in a standard <function>printf</function> call), and any following arguments are the parameters for the format string. The error levels are: </simpara> <sect2 id="internal.e-notice"> <title><constant>E_NOTICE</constant></title> <simpara> Notices are not printed by default, and indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script. For example, trying to access the value of a variable which has not been set, or calling <function>stat</function> on a file that doesn't exist. </simpara> </sect2> <sect2 id="internal.e-warning"> <title><constant>E_WARNING</constant></title> <simpara> Warnings are printed by default, but do not interrupt script execution. These indicate a problem that should have been trapped by the script before the call was made. For example, calling <function>ereg</function> with an invalid regular expression. </simpara> </sect2> <sect2 id="internal.e-error"> <title><constant>E_ERROR</constant></title> <simpara> Errors are also printed by default, and execution of the script is halted after the function returns. These indicate errors that can not be recovered from, such as a memory allocation problem. </simpara> </sect2> <sect2 id="internal.e-parse"> <title><constant>E_PARSE</constant></title> <simpara> Parse errors should only be generated by the parser. The code is listed here only for the sake of completeness. </simpara> </sect2> <sect2 id="internal.e-core-error"> <title><constant>E_CORE_ERROR</constant></title> <simpara> This is like an <constant>E_ERROR</constant>, except it is generated by the core of PHP. Functions should not generate this type of error. </simpara> </sect2> <sect2 id="internal.e-core-warning"> <title><constant>E_CORE_WARNING</constant></title> <simpara> This is like an <constant>E_WARNING</constant>, except it is generated by the core of PHP. Functions should not generate this type of error. </simpara> </sect2> <sect2 id="internal.e-compile-error"> <title><constant>E_COMPILE_ERROR</constant></title> <simpara> This is like an <constant>E_ERROR</constant>, except it is generated by the Zend Scripting Engine. Functions should not generate this type of error. </simpara> </sect2> <sect2 id="internal.e-compile-warning"> <title><constant>E_COMPILE_WARNING</constant></title> <simpara> This is like an <constant>E_WARNING</constant>, except it is generated by the Zend Scripting Engine. Functions should not generate this type of error. </simpara> </sect2> <sect2 id="internal.e-user-error"> <title><constant>E_USER_ERROR</constant></title> <simpara> This is like an <constant>E_ERROR</constant>, except it is generated in PHP code by using the PHP function <function>trigger_error</function>. Functions should not generate this type of error. </simpara> </sect2> <sect2 id="internal.e-user-warning"> <title><constant>E_USER_WARNING</constant></title> <simpara> This is like an <constant>E_WARNING</constant>, except it is generated by using the PHP function <function>trigger_error</function>. Functions should not generate this type of error. </simpara> </sect2> <sect2 id="internal.e-user-notice"> <title><constant>E_USER_NOTICE</constant></title> <simpara> This is like an <constant>E_NOTICE</constant>, except it is generated by using the PHP function <function>trigger_error</function>. Functions should not generate this type of error. </simpara> </sect2> <sect2 id="internal.e-all"> <title><constant>E_ALL</constant></title> <simpara> All of the above. Using this error_reporting level will show all error types. </simpara> </sect2> </sect1> </chapter> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/intro.xml?r=1.1&p=1 Index: phpdoc/en/internals/intro.xml +++ phpdoc/en/internals/intro.xml <?xml version="1.0" encoding="iso-8859-1"?> <!-- $Revision: 1.1 $ --> <partintro> <para> If you are about to begin developing PHP or Zend extensions, you need to prepare yourself for the programming environment provided by the various APIs. This part of the documentation tries to introduce the APIs provided by the different PHP and Zend Engine versions available. Since most of the information available here is somwehat outdated, you'll want to read various files found in the PHP source, files such as <filename>README.SELF-CONTAINED-EXTENSIONS</filename> and <filename>README.EXT_SKEL</filename> in addition to the manual. </para> </partintro> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/streams/common.xml?r=1.1&p=1 Index: phpdoc/en/internals/streams/common.xml +++ phpdoc/en/internals/streams/common.xml <?xml version="1.0" encoding="iso-8859-1"?> <!-- $Revision: 1.1 $ --> <!-- Author: Wez Furlong <wez@thebrainroom.com> Please contact me before making any major amendments to the content of this section. Splitting/Merging are fine if they are required for php-doc restructuring purposes - just drop me a line if you make a change (so I can update my local copy). --> <sect1 id="streams.common-api"> <title>Streams Common API Reference</title> <refentry id="streams.php-stream-stat-path"> <refnamediv> <refname>php_stream_stat_path</refname> <refpurpose>Gets the status for a file or URL</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>int</type><methodname>php_stream_stat_path</methodname> <methodparam><type>char *</type><parameter>path</parameter></methodparam> <methodparam><type>php_stream_statbuf *</type><parameter>ssb</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_stat_path</function> examines the file or URL specified by <parameter>path</parameter> and returns information such as file size, access and creation times and so on. The return value is 0 on success, -1 on error. For more information about the information returned, see <link linkend="streams.struct-php-stream-statbuf">php_stream_statbuf</link>. </para> </refsect1> </refentry> <refentry id="streams.php-stream-stat"> <refnamediv> <refname>php_stream_stat</refname> <refpurpose>Gets the status for the underlying storage associated with a stream</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>int</type><methodname>php_stream_stat</methodname> <methodparam><type>php_stream *</type><parameter>stream</parameter></methodparam> <methodparam><type>php_stream_statbuf *</type><parameter>ssb</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_stat</function> examines the storage to which <parameter>stream</parameter> is bound, and returns information such as file size, access and creation times and so on. The return value is 0 on success, -1 on error. For more information about the information returned, see <link linkend="streams.struct-php-stream-statbuf">php_stream_statbuf</link>. </para> </refsect1> </refentry> <refentry id="streams.php-stream-open-wrapper"> <refnamediv> <refname>php_stream_open_wrapper</refname> <refpurpose>Opens a stream on a file or URL</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>php_stream *</type><methodname>php_stream_open_wrapper</methodname> <methodparam><type>char *</type><parameter>path</parameter></methodparam> <methodparam><type>char *</type><parameter>mode</parameter></methodparam> <methodparam><type>int</type><parameter>options</parameter></methodparam> <methodparam><type>char **</type><parameter>opened</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_open_wrapper</function> opens a stream on the file, URL or other wrapped resource specified by <parameter>path</parameter>. Depending on the value of <parameter>mode</parameter>, the stream may be opened for reading, writing, appending or combinations of those. See the table below for the different modes that can be used; in addition to the characters listed below, you may include the character 'b' either as the second or last character in the mode string. The presence of the 'b' character informs the relevant stream implementation to open the stream in a binary safe mode. </para> <para> The 'b' character is ignored on all POSIX conforming systems which treat binary and text files in the same way. It is a good idea to specify the 'b' character whenever your stream is accessing data where the full 8 bits are important, so that your code will work when compiled on a system where the 'b' flag is important. </para> <para> Any local files created by the streams API will have their initial permissions set according to the operating system defaults - under Unix based systems this means that the umask of the process will be used. Under Windows, the file will be owned by the creating process. Any remote files will be created according to the URL wrapper that was used to open the file, and the credentials supplied to the remote server. </para> <para> <variablelist> <varlistentry> <term> <constant>r</constant> </term> <listitem> <simpara> Open text file for reading. The stream is positioned at the beginning of the file. </simpara> </listitem> </varlistentry> <varlistentry> <term> <constant>r+</constant> </term> <listitem> <simpara> Open text file for reading and writing. The stream is positioned at the beginning of the file. </simpara> </listitem> </varlistentry> <varlistentry> <term> <constant>w</constant> </term> <listitem> <simpara> Truncate the file to zero length or create text file for writing. The stream is positioned at the beginning of the file. </simpara> </listitem> </varlistentry> <varlistentry> <term> <constant>w+</constant> </term> <listitem> <simpara> Open text file for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file. </simpara> </listitem> </varlistentry> <varlistentry> <term> <constant>a</constant> </term> <listitem> <simpara> Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. </simpara> </listitem> </varlistentry> <varlistentry> <term> <constant>a+</constant> </term> <listitem> <simpara> Open text file for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. </simpara> </listitem> </varlistentry> </variablelist> </para> <para> <parameter>options</parameter> affects how the path/URL of the stream is interpreted, safe mode checks and actions taken if there is an error during opening of the stream. See <link linkend="streams.options">Stream open options</link> for more information about options. </para> <para> If <parameter>opened</parameter> is not NULL, it will be set to a string containing the name of the actual file/resource that was opened. This is important when the options include <constant>USE_PATH</constant>, which causes the include_path to be searched for the file. You, the caller, are responsible for calling <function>efree</function> on the filename returned in this parameter. </para> <note> <simpara> If you specified <constant>STREAM_MUST_SEEK</constant> in <parameter>options</parameter>, the path returned in <parameter>opened</parameter> may not be the name of the actual stream that was returned to you. It will, however, be the name of the original resource from which the seekable stream was manufactured. </simpara> </note> </refsect1> </refentry> <refentry id="streams.php-stream-read"> <refnamediv> <refname>php_stream_read</refname> <refpurpose>Read a number of bytes from a stream into a buffer</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>size_t</type><methodname>php_stream_read</methodname> <methodparam><type>php_stream *</type><parameter>stream</parameter></methodparam> <methodparam><type>char *</type><parameter>buf</parameter></methodparam> <methodparam><type>size_t</type><parameter>count</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_read</function> reads up to <parameter>count</parameter> bytes of data from <parameter>stream</parameter> and copies them into the buffer <parameter>buf</parameter>. </para> <para> <function>php_stream_read</function> returns the number of bytes that were read successfully. There is no distinction between a failed read or an end-of-file condition - use <function>php_stream_eof</function> to test for an <constant>EOF</constant>. </para> <para> The internal position of the stream is advanced by the number of bytes that were read, so that subsequent reads will continue reading from that point. </para> <para> If less than <parameter>count</parameter> bytes are available to be read, this call will block (or wait) until the required number are available, depending on the blocking status of the stream. By default, a stream is opened in blocking mode. When reading from regular files, the blocking mode will not usually make any difference: when the stream reaches the <constant>EOF</constant> <function>php_stream_read</function> will return a value less than <parameter>count</parameter>, and 0 on subsequent reads. </para> </refsect1> </refentry> <refentry id="streams.php-stream-write"> <refnamediv> <refname>php_stream_write</refname> <refpurpose>Write a number of bytes from a buffer to a stream</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>size_t</type><methodname>php_stream_write</methodname> <methodparam><type>php_stream *</type><parameter>stream</parameter></methodparam> <methodparam><type>const char *</type><parameter>buf</parameter></methodparam> <methodparam><type>size_t</type><parameter>count</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_write</function> writes <parameter>count</parameter> bytes of data from <parameter>buf</parameter> into <parameter>stream</parameter>. </para> <para> <function>php_stream_write</function> returns the number of bytes that were written successfully. If there was an error, the number of bytes written will be less than <parameter>count</parameter>. </para> <para> The internal position of the stream is advanced by the number of bytes that were written, so that subsequent writes will continue writing from that point. </para> </refsect1> </refentry> <refentry id="streams.php-stream-eof"> <refnamediv> <refname>php_stream_eof</refname> <refpurpose>Check for an end-of-file condition on a stream</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>int</type><methodname>php_stream_eof</methodname> <methodparam><type>php_stream *</type><parameter>stream</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_eof</function> checks for an end-of-file condition on <parameter>stream</parameter>. </para> <para> <function>php_stream_eof</function> returns the 1 to indicate <constant>EOF</constant>, 0 if there is no <constant>EOF</constant> and -1 to indicate an error. </para> </refsect1> </refentry> <refentry id="streams.php-stream-getc"> <refnamediv> <refname>php_stream_getc</refname> <refpurpose>Read a single byte from a stream</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>int</type><methodname>php_stream_getc</methodname> <methodparam><type>php_stream *</type><parameter>stream</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_getc</function> reads a single character from <parameter>stream</parameter> and returns it as an unsigned char cast as an int, or <constant>EOF</constant> if the end-of-file is reached, or an error occurred. </para> <para> <function>php_stream_getc</function> may block in the same way as <function>php_stream_read</function> blocks. </para> <para> The internal position of the stream is advanced by 1 if successful. </para> </refsect1> </refentry> <refentry id="streams.php-stream-gets"> <refnamediv> <refname>php_stream_gets</refname> <refpurpose>Read a line of data from a stream into a buffer</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>char *</type><methodname>php_stream_gets</methodname> <methodparam><type>php_stream *</type><parameter>stream</parameter></methodparam> <methodparam><type>char *</type><parameter>buf</parameter></methodparam> <methodparam><type>size_t</type><parameter>maxlen</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_gets</function> reads up to <parameter>count</parameter>-1 bytes of data from <parameter>stream</parameter> and copies them into the buffer <parameter>buf</parameter>. Reading stops after an <constant>EOF</constant> or a newline. If a newline is read, it is stored in <parameter>buf</parameter> as part of the returned data. A NUL terminating character is stored as the last character in the buffer. </para> <para> <function>php_stream_read</function> returns <parameter>buf</parameter> when successful or NULL otherwise. </para> <para> The internal position of the stream is advanced by the number of bytes that were read, so that subsequent reads will continue reading from that point. </para> <para> This function may block in the same way as <function>php_stream_read</function>. </para> </refsect1> </refentry> <refentry id="streams.php-stream-close"> <refnamediv> <refname>php_stream_close</refname> <refpurpose>Close a stream</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>int</type><methodname>php_stream_close</methodname> <methodparam><type>php_stream *</type><parameter>stream</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_close</function> safely closes <parameter>stream</parameter> and releases the resources associated with it. After <parameter>stream</parameter> has been closed, it's value is undefined and should not be used. </para> <para> <function>php_stream_close</function> returns 0 if the stream was closed or <constant>EOF</constant> to indicate an error. Regardless of the success of the call, <parameter>stream</parameter> is undefined and should not be used after a call to this function. </para> </refsect1> </refentry> <refentry id="streams.php-stream-flush"> <refnamediv> <refname>php_stream_flush</refname> <refpurpose>Flush stream buffers to storage</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>int</type><methodname>php_stream_flush</methodname> <methodparam><type>php_stream *</type><parameter>stream</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_flush</function> causes any data held in write buffers in <parameter>stream</parameter> to be committed to the underlying storage. </para> <para> <function>php_stream_flush</function> returns 0 if the buffers were flushed, or if the buffers did not need to be flushed, but returns <constant>EOF</constant> to indicate an error. </para> </refsect1> </refentry> <refentry id="streams.php-stream-seek"> <refnamediv> <refname>php_stream_seek</refname> <refpurpose>Reposition a stream</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>int</type><methodname>php_stream_seek</methodname> <methodparam><type>php_stream *</type><parameter>stream</parameter></methodparam> <methodparam><type>off_t</type><parameter>offset</parameter></methodparam> <methodparam><type>int</type><parameter>whence</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_seek</function> repositions the internal position of <parameter>stream</parameter>. The new position is determined by adding the <parameter>offset</parameter> to the position indicated by <parameter>whence</parameter>. If <parameter>whence</parameter> is set to <constant>SEEK_SET</constant>, <constant>SEEK_CUR</constant> or <constant>SEEK_END</constant> the offset is relative to the start of the stream, the current position or the end of the stream, respectively. </para> <para> <function>php_stream_seek</function> returns 0 on success, but -1 if there was an error. </para> <note> <para> Not all streams support seeking, although the streams API will emulate a seek if <parameter>whence</parameter> is set to <constant>SEEK_CUR</constant> and <parameter>offset</parameter> is positive, by calling <function>php_stream_read</function> to read (and discard) <parameter>offset</parameter> bytes. </para> <para> The emulation is only applied when the underlying stream implementation does not support seeking. If the stream is (for example) a file based stream that is wrapping a non-seekable pipe, the streams api will not apply emulation because the file based stream implements a seek operation; the seek will fail and an error result will be returned to the caller. </para> </note> </refsect1> </refentry> <refentry id="streams.php-stream-tell"> <refnamediv> <refname>php_stream_tell</refname> <refpurpose>Determine the position of a stream</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>off_t</type><methodname>php_stream_tell</methodname> <methodparam><type>php_stream *</type><parameter>stream</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_tell</function> returns the internal position of <parameter>stream</parameter>, relative to the start of the stream. If there is an error, -1 is returned. </para> </refsect1> </refentry> <refentry id="streams.php-stream-copy-to-stream"> <refnamediv> <refname>php_stream_copy_to_stream</refname> <refpurpose>Copy data from one stream to another</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>size_t</type><methodname>php_stream_copy_to_stream</methodname> <methodparam><type>php_stream *</type><parameter>src</parameter></methodparam> <methodparam><type>php_stream *</type><parameter>dest</parameter></methodparam> <methodparam><type>size_t</type><parameter>maxlen</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_copy_to_stream</function> attempts to read up to <parameter>maxlen</parameter> bytes of data from <parameter>src</parameter> and write them to <parameter>dest</parameter>, and returns the number of bytes that were successfully copied. </para> <para> If you want to copy all remaining data from the <parameter>src</parameter> stream, pass the constant <constant>PHP_STREAM_COPY_ALL</constant> as the value of <parameter>maxlen</parameter>. </para> <note> <simpara> This function will attempt to copy the data in the most efficient manner, using memory mapped files when possible. </simpara> </note> </refsect1> </refentry> <refentry id="streams.php-stream-copy-to-mem"> <refnamediv> <refname>php_stream_copy_to_mem</refname> <refpurpose>Copy data from stream and into an allocated buffer</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>size_t</type><methodname>php_stream_copy_to_mem</methodname> <methodparam><type>php_stream *</type><parameter>src</parameter></methodparam> <methodparam><type>char **</type><parameter>buf</parameter></methodparam> <methodparam><type>size_t</type><parameter>maxlen</parameter></methodparam> <methodparam><type>int</type><parameter>persistent</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_copy_to_mem</function> allocates a buffer <parameter>maxlen</parameter>+1 bytes in length using <function>pemalloc</function> (passing <parameter>persistent</parameter>). It then reads <parameter>maxlen</parameter> bytes from <parameter>src</parameter> and stores them in the allocated buffer. </para> <para> The allocated buffer is returned in <parameter>buf</parameter>, and the number of bytes successfully read. You, the caller, are responsible for freeing the buffer by passing it and <parameter>persistent</parameter> to <function>pefree</function>. </para> <para> If you want to copy all remaining data from the <parameter>src</parameter> stream, pass the constant <constant>PHP_STREAM_COPY_ALL</constant> as the value of <parameter>maxlen</parameter>. </para> <note> <simpara> This function will attempt to copy the data in the most efficient manner, using memory mapped files when possible. </simpara> </note> </refsect1> </refentry> <refentry id="streams.php-stream-make-seekable"> <refnamediv> <refname>php_stream_make_seekable</refname> <refpurpose>Convert a stream into a stream is seekable</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>int</type><methodname>php_stream_make_seekable</methodname> <methodparam><type>php_stream *</type><parameter>origstream</parameter></methodparam> <methodparam><type>php_stream **</type><parameter>newstream</parameter></methodparam> <methodparam><type>int</type><parameter>flags</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_make_seekable</function> checks if <parameter>origstream</parameter> is seekable. If it is not, it will copy the data into a new temporary stream. If successful, <parameter>newstream</parameter> is always set to the stream that is valid to use, even if the original stream was seekable. </para> <para> <parameter>flags</parameter> allows you to specify your preference for the seekable stream that is returned: use <constant>PHP_STREAM_NO_PREFERENCE</constant> to use the default seekable stream (which uses a dynamically expanding memory buffer, but switches to temporary file backed storage when the stream size becomes large), or use <constant>PHP_STREAM_PREFER_STDIO</constant> to use "regular" temporary file backed storage. </para> <para> <table> <title><function>php_stream_make_seekable</function> return values</title> <tgroup cols="2"> <thead> <row> <entry>Value</entry> <entry>Meaning</entry> </row> </thead> <tbody> <row> <entry>PHP_STREAM_UNCHANGED</entry> <entry>Original stream was seekable anyway. <parameter>newstream</parameter> is set to the value of <parameter>origstream</parameter>. </entry> </row> <row> <entry>PHP_STREAM_RELEASED</entry> <entry>Original stream was not seekable and has been released. <parameter>newstream</parameter> is set to the new seekable stream. You should not access <parameter>origstream</parameter> anymore. </entry> </row> <row> <entry>PHP_STREAM_FAILED</entry> <entry>An error occurred while attempting conversion. <parameter>newstream</parameter> is set to NULL; <parameter>origstream</parameter> is still valid. </entry> </row> <row> <entry>PHP_STREAM_CRITICAL</entry> <entry>An error occurred while attempting conversion that has left <parameter>origstream</parameter> in an indeterminate state. <parameter>newstream</parameter> is set to NULL and it is highly recommended that you close <parameter>origstream</parameter>. </entry> </row> </tbody> </tgroup> </table> </para> <note> <simpara> If you need to seek and write to the stream, it does not make sense to use this function, because the stream it returns is not guaranteed to be bound to the same resource as the original stream. </simpara> </note> <note> <simpara> If you only need to seek forwards, there is no need to call this function, as the streams API will emulate forward seeks when the whence parameter is <constant>SEEK_CUR</constant>. </simpara> </note> <note> <simpara> If <parameter>origstream</parameter> is network based, this function will block until the whole contents have been downloaded. </simpara> </note> <note> <simpara> NEVER call this function with an <parameter>origstream</parameter> that is reference by a file pointer in a PHP script! This function may cause the underlying stream to be closed which could cause a crash when the script next accesses the file pointer! </simpara> </note> <note> <simpara> In many cases, this function can only succeed when <parameter>origstream</parameter> is a newly opened stream with no data buffered in the stream layer. For that reason, and because this function is complicated to use correctly, it is recommended that you use <function>php_stream_open_wrapper</function> and pass in <constant>PHP_STREAM_MUST_SEEK</constant> in your options instead of calling this function directly. </simpara> </note> </refsect1> </refentry> <refentry id="streams.php-stream-cast"> <refnamediv> <refname>php_stream_cast</refname> <refpurpose>Convert a stream into another form, such as a FILE* or socket</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>int</type><methodname>php_stream_cast</methodname> <methodparam><type>php_stream *</type><parameter>stream</parameter></methodparam> <methodparam><type>int</type><parameter>castas</parameter></methodparam> <methodparam><type>void **</type><parameter>ret</parameter></methodparam> <methodparam><type>int</type><parameter>flags</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_cast</function> attempts to convert <parameter>stream</parameter> into a resource indicated by <parameter>castas</parameter>. If <parameter>ret</parameter> is NULL, the stream is queried to find out if such a conversion is possible, without actually performing the conversion (however, some internal stream state *might* be changed in this case). If <parameter>flags</parameter> is set to <constant>REPORT_ERRORS</constant>, an error message will be displayed is there is an error during conversion. </para> <note> <para> This function returns <constant>SUCCESS</constant> for success or <constant>FAILURE</constant> for failure. Be warned that you must explicitly compare the return value with <constant>SUCCESS</constant> or <constant>FAILURE</constant> because of the underlying values of those constants. A simple boolean expression will not be interpreted as you intended. </para> </note> <para> <table> <title>Resource types for <parameter>castas</parameter></title> <tgroup cols="2"> <thead> <row> <entry>Value</entry> <entry>Meaning</entry> </row> </thead> <tbody> <row> <entry>PHP_STREAM_AS_STDIO</entry> <entry>Requests an ANSI FILE* that represents the stream</entry> </row> <row> <entry>PHP_STREAM_AS_FD</entry> <entry>Requests a POSIX file descriptor that represents the stream</entry> </row> <row> <entry>PHP_STREAM_AS_SOCKETD</entry> <entry>Requests a network socket descriptor that represents the stream</entry> </row> </tbody> </tgroup> </table> </para> <para> In addition to the basic resource types above, the conversion process can be altered by using the following flags by using the OR operator to combine the resource type with one or more of the following values: <table> <title>Resource types for <parameter>castas</parameter></title> <tgroup cols="2"> <thead> <row> <entry>Value</entry> <entry>Meaning</entry> </row> </thead> <tbody> <row> <entry>PHP_STREAM_CAST_TRY_HARD</entry> <entry>Tries as hard as possible, at the expense of additional resources, to ensure that the conversion succeeds</entry> </row> <row> <entry>PHP_STREAM_CAST_RELEASE</entry> <entry>Informs the streams API that some other code (possibly a third party library) will be responsible for closing the underlying handle/resource. This causes the <parameter>stream</parameter> to be closed in such a way the underlying handle is preserved and returned in <parameter>ret</parameter>. If this function succeeds, <parameter>stream</parameter> should be considered closed and should no longer be used. </entry> </row> </tbody> </tgroup> </table> </para> <note> <simpara> If your system supports <function>fopencookie</function> (systems using glibc 2 or later), the streams API will always be able to synthesize an ANSI FILE* pointer over any stream. While this is tremendously useful for passing any PHP stream to any third-party libraries, such behaviour is not portable. You are requested to consider the portability implications before distributing you extension. If the fopencookie synthesis is not desirable, you should query the stream to see if it naturally supports FILE* by using <function>php_stream_is</function> </simpara> </note> <note> <simpara> If you ask a socket based stream for a FILE*, the streams API will use <function>fdopen</function> to create it for you. Be warned that doing so may cause data that was buffered in the streams layer to be lost if you intermix streams API calls with ANSI stdio calls. </simpara> </note> <para> See also <function>php_stream_is</function> and <function>php_stream_can_cast</function>. </para> </refsect1> </refentry> <refentry id="streams.php-stream-can-cast"> <refnamediv> <refname>php_stream_can_cast</refname> <refpurpose>Determines if a stream can be converted into another form, such as a FILE* or socket</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>int</type><methodname>php_stream_can_cast</methodname> <methodparam><type>php_stream *</type><parameter>stream</parameter></methodparam> <methodparam><type>int</type><parameter>castas</parameter></methodparam> </methodsynopsis> <para> This function is equivalent to calling <function>php_stream_cast</function> with <parameter>ret</parameter> set to NULL and <parameter>flags</parameter> set to 0. It returns <constant>SUCCESS</constant> if the stream can be converted into the form requested, or <constant>FAILURE</constant> if the conversion cannot be performed. </para> <note> <simpara> Although this function will not perform the conversion, some internal stream state *might* be changed by this call. </simpara> </note> <note> <simpara> You must explicitly compare the return value of this function with one of the constants, as described in <function>php_stream_cast</function>. </simpara> </note> <para> See also <function>php_stream_cast</function> and <function>php_stream_is</function>. </para> </refsect1> </refentry> <refentry id="streams.php-stream-is-persistent"> <refnamediv> <refname>php_stream_is_persistent</refname> <refpurpose>Determines if a stream is a persistent stream</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>int</type><methodname>php_stream_is_persistent</methodname> <methodparam><type>php_stream *</type><parameter>stream</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_is_persistent</function> returns 1 if the stream is a persistent stream, 0 otherwise. </para> </refsect1> </refentry> <refentry id="streams.php-stream-is"> <refnamediv> <refname>php_stream_is</refname> <refpurpose>Determines if a stream is of a particular type</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>int</type><methodname>php_stream_is</methodname> <methodparam><type>php_stream *</type><parameter>stream</parameter></methodparam> <methodparam><type>int</type><parameter>istype</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_is</function> returns 1 if <parameter>stream</parameter> is of the type specified by <parameter>istype</parameter>, or 0 otherwise. <table> <title>Values for <parameter>istype</parameter></title> <tgroup cols="2"> <thead> <row> <entry>Value</entry> <entry>Meaning</entry> </row> </thead> <tbody> <row> <entry>PHP_STREAM_IS_STDIO</entry> <entry>The stream is implemented using the stdio implementation</entry> </row> <row> <entry>PHP_STREAM_IS_SOCKET</entry> <entry>The stream is implemented using the network socket implementation</entry> </row> <row> <entry>PHP_STREAM_IS_USERSPACE</entry> <entry>The stream is implemented using the userspace object implementation</entry> </row> <row> <entry>PHP_STREAM_IS_MEMORY</entry> <entry>The stream is implemented using the grow-on-demand memory stream implementation</entry> </row> </tbody> </tgroup> </table> </para> <note> <simpara> The PHP_STREAM_IS_XXX "constants" are actually defined as pointers to the underlying stream operations structure. If your extension (or some other extension) defines additional streams, it should also declare a PHP_STREAM_IS_XXX constant in it's header file that you can use as the basis of this comparison. </simpara> </note> <note> <simpara> This function is implemented as a simple (and fast) pointer comparison, and does not change the stream state in any way. </simpara> </note> <para> See also <function>php_stream_cast</function> and <function>php_stream_can_cast</function>. </para> </refsect1> </refentry> <refentry id="streams.php-stream-passthru"> <refnamediv> <refname>php_stream_passthru</refname> <refpurpose>Outputs all remaining data from a stream</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>size_t</type><methodname>php_stream_passthru</methodname> <methodparam><type>php_stream *</type><parameter>stream</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_passthru</function> outputs all remaining data from <parameter>stream</parameter> to the active output buffer and returns the number of bytes output. If buffering is disabled, the data is written straight to the output, which is the browser making the request in the case of PHP on a web server, or stdout for CLI based PHP. This function will use memory mapped files if possible to help improve performance. </para> </refsect1> </refentry> <refentry id="streams.php-register-url-stream-wrapper"> <refnamediv> <refname>php_register_url_stream_wrapper</refname> <refpurpose>Registers a wrapper with the Streams API</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>int</type><methodname>php_register_url_stream_wrapper</methodname> <methodparam><type>char *</type><parameter>protocol</parameter></methodparam> <methodparam><type>php_stream_wrapper *</type><parameter>wrapper</parameter></methodparam> <methodparam><type>TSRMLS_DC</type><parameter></parameter></methodparam> </methodsynopsis> <para> <function>php_register_url_stream_wrapper</function> registers <parameter>wrapper</parameter> as the handler for the protocol specified by <parameter>protocol</parameter>. </para> <note> <simpara> If you call this function from a loadable module, you *MUST* call <function>php_unregister_url_stream_wrapper</function> in your module shutdown function, otherwise PHP will crash. </simpara> </note> </refsect1> </refentry> <refentry id="streams.php-unregister-url-stream-wrapper"> <refnamediv> <refname>php_unregister_url_stream_wrapper</refname> <refpurpose>Unregisters a wrapper from the Streams API</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>int</type><methodname>php_unregister_url_stream_wrapper</methodname> <methodparam><type>char *</type><parameter>protocol</parameter></methodparam> <methodparam><type>TSRMLS_DC</type><parameter></parameter></methodparam> </methodsynopsis> <para> <function>php_unregister_url_stream_wrapper</function> unregisters the wrapper associated with <parameter>protocol</parameter>. </para> </refsect1> </refentry> <refentry id="streams.php-stream-open-wrapper-ex"> <refnamediv> <refname>php_stream_open_wrapper_ex</refname> <refpurpose>Opens a stream on a file or URL, specifying context</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>php_stream *</type><methodname>php_stream_open_wrapper_ex</methodname> <methodparam><type>char *</type><parameter>path</parameter></methodparam> <methodparam><type>char *</type><parameter>mode</parameter></methodparam> <methodparam><type>int</type><parameter>options</parameter></methodparam> <methodparam><type>char **</type><parameter>opened</parameter></methodparam> <methodparam><type>php_stream_context *</type><parameter>context</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_open_wrapper_ex</function> is exactly like <function>php_stream_open_wrapper</function>, but allows you to specify a php_stream_context object using <parameter>context</parameter>. To find out more about stream contexts, see <link linkend="stream.contexts">Stream Contexts</link>. </para> </refsect1> </refentry> <refentry id="streams.php-stream-open-wrapper-as-file"> <refnamediv> <refname>php_stream_open_wrapper_as_file</refname> <refpurpose>Opens a stream on a file or URL, and converts to a FILE*</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>FILE *</type><methodname>php_stream_open_wrapper_as_file</methodname> <methodparam><type>char *</type><parameter>path</parameter></methodparam> <methodparam><type>char *</type><parameter>mode</parameter></methodparam> <methodparam><type>int</type><parameter>options</parameter></methodparam> <methodparam><type>char **</type><parameter>opened</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_open_wrapper_as_file</function> is exactly like <function>php_stream_open_wrapper</function>, but converts the stream into an ANSI stdio FILE* and returns that instead of the stream. This is a convenient shortcut for extensions that pass FILE* to third-party libraries. </para> </refsect1> </refentry> <refentry id="streams.php-stream-filter-register-factory"> <refnamediv> <refname>php_stream_filter_register_factory</refname> <refpurpose>Registers a filter factory with the Streams API</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>int</type><methodname>php_stream_filter_register_factory</methodname> <methodparam><type>const char *</type><parameter>filterpattern</parameter></methodparam> <methodparam><type>php_stream_filter_factory *</type><parameter>factory</parameter></methodparam> </methodsynopsis> <para> Use this function to register a filter factory with the name given by <parameter>filterpattern</parameter>. <parameter>filterpattern</parameter> can be either a normal string name (i.e. <literal>myfilter</literal>) or a global pattern (i.e. <literal>myfilterclass.*</literal>) to allow a single filter to perform different operations depending on the exact name of the filter invoked (i.e. <literal>myfilterclass.foo</literal>, <literal>myfilterclass.bar</literal>, etc...) </para> <note> <simpara> Filters registered by a loadable extension must be certain to call php_stream_filter_unregister_factory() during MSHUTDOWN. </simpara> </note> </refsect1> </refentry> <refentry id="streams.php-stream-filter-unregister-factory"> <refnamediv> <refname>php_stream_filter_unregister_factory</refname> <refpurpose>Deregisters a filter factory with the Streams API</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis role="c"> <type>int</type><methodname>php_stream_filter_unregister_factory</methodname> <methodparam><type>const char *</type><parameter>filterpattern</parameter></methodparam> </methodsynopsis> <para> Deregisters the <parameter>filterfactory</parameter> specified by the <parameter>filterpattern</parameter> making it no longer available for use. </para> <note> <simpara> Filters registered by a loadable extension must be certain to call php_stream_filter_unregister_factory() during MSHUTDOWN. </simpara> </note> </refsect1> </refentry> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/streams/constants.xml?r=1.1&p=1 Index: phpdoc/en/internals/streams/constants.xml +++ phpdoc/en/internals/streams/constants.xml <?xml version="1.0" encoding="iso-8859-1"?> <!-- $Revision: 1.1 $ --> <!-- Author: Wez Furlong <wez@thebrainroom.com> Please contact me before making any major amendments to the content of this section. Splitting/Merging are fine if they are required for php-doc restructuring purposes - just drop me a line if you make a change (so I can update my local copy). --> <sect1 id="streams.constants"> <title>Streams Constants</title> <refentry id="streams.options"> <refnamediv> <refname>Stream open options</refname> <refpurpose>Affects the operation of stream factory functions</refpurpose> </refnamediv> <refsect1> <title>Description</title> <para> One or more of these values can be combined using the OR operator. <variablelist> <varlistentry> <term> <constant>IGNORE_PATH</constant> </term> <listitem> <simpara> This is the default option for streams; it requests that the include_path is not to be searched for the requested file. </simpara> </listitem> </varlistentry> <varlistentry> <term> <constant>USE_PATH</constant> </term> <listitem> <simpara> Requests that the include_path is to be searched for the requested file. </simpara> </listitem> </varlistentry> <varlistentry> <term> <constant>IGNORE_URL</constant> </term> <listitem> <simpara> Requests that registered URL wrappers are to be ignored when opening the stream. Other non-URL wrappers will be taken into consideration when decoding the path. There is no opposite form for this flag; the streams API will use all registered wrappers by default. </simpara> </listitem> </varlistentry> <varlistentry> <term> <constant>IGNORE_URL_WIN</constant> </term> <listitem> <simpara> On Windows systems, this is equivalent to IGNORE_URL. On all other systems, this flag has no effect. </simpara> </listitem> </varlistentry> <varlistentry> <term> <constant>ENFORCE_SAFE_MODE</constant> </term> <listitem> <simpara> Requests that the underlying stream implementation perform safe_mode checks on the file before opening the file. Omitting this flag will skip safe_mode checks and allow opening of any file that the PHP process has rights to access. </simpara> </listitem> </varlistentry> <varlistentry> <term> <constant>REPORT_ERRORS</constant> </term> <listitem> <simpara> If this flag is set, and there was an error during the opening of the file or URL, the streams API will call the php_error function for you. This is useful because the path may contain username/password information that should not be displayed in the browser output (it would be a security risk to do so). When the streams API raises the error, it first strips username/password information from the path, making the error message safe to display in the browser. </simpara> </listitem> </varlistentry> <varlistentry> <term> <constant>STREAM_MUST_SEEK</constant> </term> <listitem> <simpara> This flag is useful when your extension really must be able to randomly seek around in a stream. Some streams may not be seekable in their native form, so this flag asks the streams API to check to see if the stream does support seeking. If it does not, it will copy the stream into temporary storage (which may be a temporary file or a memory stream) which does support seeking. Please note that this flag is not useful when you want to seek the stream and write to it, because the stream you are accessing might not be bound to the actual resource you requested. </simpara> <note> <simpara> If the requested resource is network based, this flag will cause the opener to block until the whole contents have been downloaded. </simpara> </note> </listitem> </varlistentry> <varlistentry> <term> <constant>STREAM_WILL_CAST</constant> </term> <listitem> <simpara> If your extension is using a third-party library that expects a FILE* or file descriptor, you can use this flag to request the streams API to open the resource but avoid buffering. You can then use <function>php_stream_cast</function> to retrieve the FILE* or file descriptor that the library requires. </simpara> <simpara> The is particularly useful when accessing HTTP URLs where the start of the actual stream data is found after an indeterminate offset into the stream. </simpara> <simpara> Since this option disables buffering at the streams API level, you may experience lower performance when using streams functions on the stream; this is deemed acceptable because you have told streams that you will be using the functions to match the underlying stream implementation. Only use this option when you are sure you need it. </simpara> </listitem> </varlistentry> </variablelist> </para> </refsect1> </refentry> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/streams/dir.xml?r=1.1&p=1 Index: phpdoc/en/internals/streams/dir.xml +++ phpdoc/en/internals/streams/dir.xml <?xml version="1.0" encoding="iso-8859-1"?> <!-- $Revision: 1.1 $ --> <!-- Author: Wez Furlong <wez@thebrainroom.com> Please contact me before making any major amendments to the content of this section. Splitting/Merging are fine if they are required for php-doc restructuring purposes - just drop me a line if you make a change (so I can update my local copy). --> <sect1 id="streams.dir-api"> <title>Streams Dir API Reference</title> <para> The functions listed in this section work on local files, as well as remote files (provided that the wrapper supports this functionality!). </para> <refentry id="streams.php-stream-opendir"> <refnamediv> <refname>php_stream_opendir</refname> <refpurpose>Open a directory for file enumeration</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis> <type>php_stream *</type><methodname>php_stream_opendir</methodname> <methodparam><type>char *</type><parameter>path</parameter></methodparam> <methodparam><type>php_stream_context *</type><parameter>context</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_opendir</function> returns a stream that can be used to list the files that are contained in the directory specified by <parameter>path</parameter>. This function is functionally equivalent to POSIX <function>opendir</function>. Although this function returns a php_stream object, it is not recommended to try to use the functions from the common API on these streams. </para> </refsect1> </refentry> <refentry id="streams.php-stream-readdir"> <refnamediv> <refname>php_stream_readdir</refname> <refpurpose>Fetch the next directory entry from an opened dir</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis> <type>php_stream_dirent *</type><methodname>php_stream_readdir</methodname> <methodparam><type>php_stream *</type><parameter>dirstream</parameter></methodparam> <methodparam><type>php_stream_dirent *</type><parameter>ent</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_readdir</function> reads the next directory entry from <parameter>dirstream</parameter> and stores it into <parameter>ent</parameter>. If the function succeeds, the return value is <parameter>ent</parameter>. If the function fails, the return value is NULL. See <link linkend="streams.struct-php-stream-dirent">php_stream_dirent</link> for more details about the information returned for each directory entry. </para> </refsect1> </refentry> <refentry id="streams.php-stream-rewinddir"> <refnamediv> <refname>php_stream_rewinddir</refname> <refpurpose>Rewind a directory stream to the first entry</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis> <type>int</type><methodname>php_stream_rewinddir</methodname> <methodparam><type>php_stream *</type><parameter>dirstream</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_rewinddir</function> rewinds a directory stream to the first entry. Returns 0 on success, but -1 on failure. </para> </refsect1> </refentry> <refentry id="streams.php-stream-closedir"> <refnamediv> <refname>php_stream_closedir</refname> <refpurpose>Close a directory stream and release resources</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis> <type>int</type><methodname>php_stream_closedir</methodname> <methodparam><type>php_stream *</type><parameter>dirstream</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_closedir</function> closes a directory stream and releases resources associated with it. Returns 0 on success, but -1 on failure. </para> </refsect1> </refentry> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/streams/file.xml?r=1.1&p=1 Index: phpdoc/en/internals/streams/file.xml +++ phpdoc/en/internals/streams/file.xml <?xml version="1.0" encoding="iso-8859-1"?> <!-- $Revision: 1.1 $ --> <!-- Author: Wez Furlong <wez@thebrainroom.com> Please contact me before making any major amendments to the content of this section. Splitting/Merging are fine if they are required for php-doc restructuring purposes - just drop me a line if you make a change (so I can update my local copy). --> <sect1 id="streams.file-api"> <title>Streams File API Reference</title> <refentry id="streams.php-stream-fopen-from-file"> <refnamediv> <refname>php_stream_fopen_from_file</refname> <refpurpose>Convert an ANSI FILE* into a stream</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis> <type>php_stream *</type><methodname>php_stream_fopen_from_file</methodname> <methodparam><type>FILE *</type><parameter>file</parameter></methodparam> <methodparam><type>char *</type><parameter>mode</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_fopen_from_file</function> returns a stream based on the <parameter>file</parameter>. <parameter>mode</parameter> must be the same as the mode used to open <parameter>file</parameter>, otherwise strange errors may occur when trying to write when the mode of the stream is different from the mode on the file. </para> </refsect1> </refentry> <refentry id="streams.php-stream-fopen-tmpfile"> <refnamediv> <refname>php_stream_fopen_tmpfile</refname> <refpurpose>Open a FILE* with tmpfile() and convert into a stream</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis> <type>php_stream *</type><methodname>php_stream_fopen_tmpfile</methodname> <methodparam><type>void</type><parameter></parameter></methodparam> </methodsynopsis> <para> <function>php_stream_fopen_tmpfile</function> returns a stream based on a temporary file opened with a mode of "w+b". The temporary file will be deleted automatically when the stream is closed or the process terminates. </para> </refsect1> </refentry> <refentry id="streams.php-stream-fopen-temporary-file"> <refnamediv> <refname>php_stream_fopen_temporary_file</refname> <refpurpose>Generate a temporary file name and open a stream on it</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis> <type>php_stream *</type><methodname>php_stream_fopen_temporary_file</methodname> <methodparam><type>const char *</type><parameter>dir</parameter></methodparam> <methodparam><type>const char *</type><parameter>pfx</parameter></methodparam> <methodparam><type>char **</type><parameter>opened</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_fopen_temporary_file</function> generates a temporary file name in the directory specified by <parameter>dir</parameter> and with a prefix of <parameter>pfx</parameter>. The generated file name is returns in the <parameter>opened</parameter> parameter, which you are responsible for cleaning up using <function>efree</function>. A stream is opened on that generated filename in "w+b" mode. The file is NOT automatically deleted; you are responsible for unlinking or moving the file when you have finished with it. </para> </refsect1> </refentry> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/streams/index.xml?r=1.1&p=1 Index: phpdoc/en/internals/streams/index.xml +++ phpdoc/en/internals/streams/index.xml <?xml version="1.0" encoding="iso-8859-1"?> <!-- $Revision: 1.1 $ --> <!-- Author: Wez Furlong <wez@thebrainroom.com> Please contact me before making any major amendments to the content of this section. Splitting/Merging are fine if they are required for php-doc restructuring purposes - just drop me a line if you make a change (so I can update my local copy). --> <chapter id="streams"> <title>Streams API for PHP Extension Authors</title> <sect1 id="streams.overview"> <title>Overview</title> <para> The PHP Streams API introduces a unified approach to the handling of files and sockets in PHP extension. Using a single API with standard functions for common operations, the streams API allows your extension to access files, sockets, URLs, memory and script-defined objects. Streams is a run-time extensible API that allows dynamically loaded modules (and scripts!) to register new streams. </para> <para> The aim of the Streams API is to make it comfortable for developers to open files, URLs and other streamable data sources with a unified API that is easy to understand. The API is more or less based on the ANSI C stdio family of functions (with identical semantics for most of the main functions), so C programmers will have a feeling of familiarity with streams. </para> <para> The streams API operates on a couple of different levels: at the base level, the API defines php_stream objects to represent streamable data sources. On a slightly higher level, the API defines php_stream_wrapper objects which "wrap" around the lower level API to provide support for retrieving data and meta-data from URLs. An additional <literal>context</literal> parameter, accepted by most stream creation functions, is passed to the wrapper's <literal>stream_opener</literal> method to fine-tune the behavior of the wrapper. </para> <para> Any stream, once opened, can also have any number of <literal>filters</literal> applied to it, which process data as it is read from/written to the stream. </para> <para> Streams can be cast (converted) into other types of file-handles, so that they can be used with third-party libraries without a great deal of trouble. This allows those libraries to access data directly from URL sources. If your system has the <function>fopencookie</function> or <function>funopen</function> function, you can even pass any PHP stream to any library that uses ANSI stdio! </para> <para> <note> <para> The functions in this chapter are for use in the PHP source code and are not PHP functions. Userland stream functions can be found in the <link linkend="ref.stream">Stream Reference</link>. </para> </note> </para> </sect1> <sect1 id="streams.basics"> <title>Streams Basics</title> <para> Using streams is very much like using ANSI stdio functions. The main difference is in how you obtain the stream handle to begin with. In most cases, you will use <function>php_stream_open_wrapper</function> to obtain the stream handle. This function works very much like fopen, as can be seen from the example below: </para> <para> <example> <title>simple stream example that displays the PHP home page</title> <programlisting role="c"> <![CDATA[ php_stream * stream = php_stream_open_wrapper("http://www.php.net", "rb", REPORT_ERRORS, NULL); if (stream) { while(!php_stream_eof(stream)) { char buf[1024]; if (php_stream_gets(stream, buf, sizeof(buf))) { printf(buf); } else { break; } } php_stream_close(stream); } ]]> </programlisting> </example> </para> <para> The table below shows the Streams equivalents of the more common ANSI stdio functions. Unless noted otherwise, the semantics of the functions are identical. <table> <title>ANSI stdio equivalent functions in the Streams API</title> <tgroup cols="3"> <thead> <row> <entry>ANSI Stdio Function</entry> <entry>PHP Streams Function</entry> <entry>Notes</entry> </row> </thead> <tbody> <row> <entry>fopen</entry> <entry>php_stream_open_wrapper</entry> <entry>Streams includes additional parameters</entry> </row> <row> <entry>fclose</entry> <entry>php_stream_close</entry> <entry></entry> </row> <row> <entry>fgets</entry> <entry>php_stream_gets</entry> <entry></entry> </row> <row> <entry>fread</entry> <entry>php_stream_read</entry> <entry>The nmemb parameter is assumed to have a value of 1, so the prototype looks more like read(2)</entry> </row> <row> <entry>fwrite</entry> <entry>php_stream_write</entry> <entry>The nmemb parameter is assumed to have a value of 1, so the prototype looks more like write(2)</entry> </row> <row> <entry>fseek</entry> <entry>php_stream_seek</entry> <entry></entry> </row> <row> <entry>ftell</entry> <entry>php_stream_tell</entry> <entry></entry> </row> <row> <entry>rewind</entry> <entry>php_stream_rewind</entry> <entry></entry> </row> <row> <entry>feof</entry> <entry>php_stream_eof</entry> <entry></entry> </row> <row> <entry>fgetc</entry> <entry>php_stream_getc</entry> <entry></entry> </row> <row> <entry>fputc</entry> <entry>php_stream_putc</entry> <entry></entry> </row> <row> <entry>fflush</entry> <entry>php_stream_flush</entry> <entry></entry> </row> <row> <entry>puts</entry> <entry>php_stream_puts</entry> <entry>Same semantics as puts, NOT fputs</entry> </row> <row> <entry>fstat</entry> <entry>php_stream_stat</entry> <entry>Streams has a richer stat structure</entry> </row> </tbody> </tgroup> </table> </para> </sect1> <sect1 id="streams.resources"> <title>Streams as Resources</title> <para> All streams are registered as resources when they are created. This ensures that they will be properly cleaned up even if there is some fatal error. All of the filesystem functions in PHP operate on streams resources - that means that your extensions can accept regular PHP file pointers as parameters to, and return streams from their functions. The streams API makes this process as painless as possible: </para> <para> <example> <title>How to accept a stream as a parameter</title> <programlisting role="c"> <![CDATA[ PHP_FUNCTION(example_write_hello) { zval *zstream; php_stream *stream; if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zstream)) return; php_stream_from_zval(stream, &zstream); /* you can now use the stream. However, you do not "own" the stream, the script does. That means you MUST NOT close the stream, because it will cause PHP to crash! */ php_stream_write(stream, "hello\n"); RETURN_TRUE(); } ]]> </programlisting> </example> </para> <para> <example> <title>How to return a stream from a function</title> <programlisting role="c"> <![CDATA[ PHP_FUNCTION(example_open_php_home_page) { php_stream *stream; stream = php_stream_open_wrapper("http://www.php.net", "rb", REPORT_ERRORS, NULL); php_stream_to_zval(stream, return_value); /* after this point, the stream is "owned" by the script. If you close it now, you will crash PHP! */ } ]]> </programlisting> </example> </para> <para> Since streams are automatically cleaned up, it's tempting to think that we can get away with being sloppy programmers and not bother to close the streams when we are done with them. Although such an approach might work, it is not a good idea for a number of reasons: streams hold locks on system resources while they are open, so leaving a file open after you have finished with it could prevent other processes from accessing it. If a script deals with a large number of files, the accumulation of the resources used, both in terms of memory and the sheer number of open files, can cause web server requests to fail. Sounds bad, doesn't it? The streams API includes some magic that helps you to keep your code clean - if a stream is not closed by your code when it should be, you will find some helpful debugging information in you web server error log. </para> <note> <simpara> Always use a debug build of PHP when developing an extension (<option>--enable-debug</option> when running configure), as a lot of effort has been made to warn you about memory and stream leaks. </simpara> </note> <para> In some cases, it is useful to keep a stream open for the duration of a request, to act as a log or trace file for example. Writing the code to safely clean up such a stream is not difficult, but it's several lines of code that are not strictly needed. To save yourself the trouble of writing the code, you can mark a stream as being OK for auto cleanup. What this means is that the streams API will not emit a warning when it is time to auto-cleanup a stream. To do this, you can use <function>php_stream_auto_cleanup</function>. </para> </sect1> &internals.streams.common; &internals.streams.dir; &internals.streams.file; &internals.streams.socket; &internals.streams.structs; &internals.streams.constants; </chapter> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/streams/socket.xml?r=1.1&p=1 Index: phpdoc/en/internals/streams/socket.xml +++ phpdoc/en/internals/streams/socket.xml <?xml version="1.0" encoding="iso-8859-1"?> <!-- $Revision: 1.1 $ --> <!-- Author: Wez Furlong <wez@thebrainroom.com> Please contact me before making any major amendments to the content of this section. Splitting/Merging are fine if they are required for php-doc restructuring purposes - just drop me a line if you make a change (so I can update my local copy). --> <sect1 id="streams.socket-api"> <title>Streams Socket API Reference</title> <refentry id="streams.php-stream-sock-open-from-socket"> <refnamediv> <refname>php_stream_sock_open_from_socket</refname> <refpurpose>Convert a socket descriptor into a stream</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis> <type>php_stream *</type><methodname>php_stream_sock_open_from_socket</methodname> <methodparam><type>int</type><parameter>socket</parameter></methodparam> <methodparam><type>int</type><parameter>persistent</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_sock_open_from_socket</function> returns a stream based on the <parameter>socket</parameter>. <parameter>persistent</parameter> is a flag that controls whether the stream is opened as a persistent stream. Generally speaking, this parameter will usually be 0. </para> </refsect1> </refentry> <refentry id="streams.php-stream-sock-open-host"> <refnamediv> <refname>php_stream_sock_open_host</refname> <refpurpose>Open a connection to a host and return a stream</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis> <type>php_stream *</type><methodname>php_stream_sock_open_host</methodname> <methodparam><type>const char *</type><parameter>host</parameter></methodparam> <methodparam><type>unsigned short</type><parameter>port</parameter></methodparam> <methodparam><type>int</type><parameter>socktype</parameter></methodparam> <methodparam><type>struct timeval *</type><parameter>timeout</parameter></methodparam> <methodparam><type>int</type><parameter>persistent</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_sock_open_host</function> establishes a connect to the specified <parameter>host</parameter> and <parameter>port</parameter>. <parameter>socktype</parameter> specifies the connection semantics that should apply to the connection. Values for <parameter>socktype</parameter> are system dependent, but will usually include (at a minimum) <constant>SOCK_STREAM</constant> for sequenced, reliable, two-way connection based streams (TCP), or <constant>SOCK_DGRAM</constant> for connectionless, unreliable messages of a fixed maximum length (UDP). </para> <para> <parameter>persistent</parameter> is a flag the controls whether the stream is opened as a persistent stream. Generally speaking, this parameter will usually be 0. </para> <para> If not NULL, <parameter>timeout</parameter> specifies a maximum time to allow for the connection to be made. If the connection attempt takes longer than the timeout value, the connection attempt is aborted and NULL is returned to indicate that the stream could not be opened. </para> <note> <simpara> The timeout value does not include the time taken to perform a DNS lookup. The reason for this is because there is no portable way to implement a non-blocking DNS lookup. </simpara> <simpara> The timeout only applies to the connection phase; if you need to set timeouts for subsequent read or write operations, you should use <function>php_stream_sock_set_timeout</function> to configure the timeout duration for your stream once it has been opened. </simpara> </note> <para> The streams API places no restrictions on the values you use for <parameter>socktype</parameter>, but encourages you to consider the portability of values you choose before you release your extension. </para> </refsect1> </refentry> <refentry id="streams.php-stream-sock-open-unix"> <refnamediv> <refname>php_stream_sock_open_unix</refname> <refpurpose>Open a Unix domain socket and convert into a stream</refpurpose> </refnamediv> <refsect1> <title>Description</title> <methodsynopsis> <type>php_stream *</type><methodname>php_stream_sock_open_unix</methodname> <methodparam><type>const char *</type><parameter>path</parameter></methodparam> <methodparam><type>int</type><parameter>pathlen</parameter></methodparam> <methodparam><type>int</type><parameter>persistent</parameter></methodparam> <methodparam><type>struct timeval *</type><parameter>timeout</parameter></methodparam> </methodsynopsis> <para> <function>php_stream_sock_open_unix</function> attempts to open the Unix domain socket specified by <parameter>path</parameter>. <parameter>pathlen</parameter> specifies the length of <parameter>path</parameter>. If <parameter>timeout</parameter> is not NULL, it specifies a timeout period for the connection attempt. <parameter>persistent</parameter> indicates if the stream should be opened as a persistent stream. Generally speaking, this parameter will usually be 0. </para> <note> <simpara> This function will not work under Windows, which does not implement Unix domain sockets. A possible exception to this rule is if your PHP binary was built using cygwin. You are encouraged to consider this aspect of the portability of your extension before it's release. </simpara> </note> <note> <simpara> This function treats <parameter>path</parameter> in a binary safe manner, suitable for use on systems with an abstract namespace (such as Linux), where the first character of path is a NUL character. </simpara> </note> </refsect1> </refentry> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/streams/structs.xml?r=1.1&p=1 Index: phpdoc/en/internals/streams/structs.xml +++ phpdoc/en/internals/streams/structs.xml <?xml version="1.0" encoding="iso-8859-1"?> <!-- $Revision: 1.1 $ --> <!-- Author: Wez Furlong <wez@thebrainroom.com> Please contact me before making any major amendments to the content of this section. Splitting/Merging are fine if they are required for php-doc restructuring purposes - just drop me a line if you make a change (so I can update my local copy). --> <sect1 id="streams.structs"> <title>Streams Structures</title> <refentry id="streams.struct-php-stream-statbuf"> <refnamediv> <refname>struct php_stream_statbuf</refname> <refpurpose>Holds information about a file or URL</refpurpose> </refnamediv> <refsect1> <title>Description</title> <synopsis> <structname>php_stream_statbuf</structname> <type>struct stat</type> <structfield>sb</structfield> </synopsis> <para> <structfield>sb</structfield> is a regular, system defined, struct stat. </para> </refsect1> </refentry> <refentry id="streams.struct-php-stream-dirent"> <refnamediv> <refname>struct php_stream_dirent</refname> <refpurpose>Holds information about a single file during dir scanning</refpurpose> </refnamediv> <refsect1> <title>Description</title> <synopsis> <structname>php_stream_dirent</structname> <type>char</type> <structfield>d_name[MAXPATHLEN]</structfield> </synopsis> <para> <structfield>d_name</structfield> holds the name of the file, relative to the directory being scanned. </para> </refsect1> </refentry> <refentry id="streams.struct-php-stream-ops"> <refnamediv> <refname>struct php_stream_ops</refname> <refpurpose>Holds member functions for a stream implementation</refpurpose> </refnamediv> <refsect1> <title>Description</title> <programlisting role="c"> <![CDATA[ typedef struct _php_stream_ops { /* all streams MUST implement these operations */ size_t (*write)(php_stream *stream, const char *buf, size_t count TSRMLS_DC); size_t (*read)(php_stream *stream, char *buf, size_t count TSRMLS_DC); int (*close)(php_stream *stream, int close_handle TSRMLS_DC); int (*flush)(php_stream *stream TSRMLS_DC); const char *label; /* name describing this class of stream */ /* these operations are optional, and may be set to NULL if the stream does not * support a particular operation */ int (*seek)(php_stream *stream, off_t offset, int whence TSRMLS_DC); char *(*gets)(php_stream *stream, char *buf, size_t size TSRMLS_DC); int (*cast)(php_stream *stream, int castas, void **ret TSRMLS_DC); int (*stat)(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC); } php_stream_ops; ]]> </programlisting> </refsect1> </refentry> <refentry id="streams.struct-php-stream-wrapper"> <refnamediv> <refname>struct php_stream_wrapper</refname> <refpurpose>Holds wrapper properties and pointer to operations</refpurpose> </refnamediv> <refsect1> <title>Description</title> <programlisting role="c"> <![CDATA[ struct _php_stream_wrapper { php_stream_wrapper_ops *wops; /* operations the wrapper can perform */ void *abstract; /* context for the wrapper */ int is_url; /* so that PG(allow_url_fopen) can be respected */ /* support for wrappers to return (multiple) error messages to the stream opener */ int err_count; char **err_stack; } php_stream_wrapper; ]]> </programlisting> </refsect1> </refentry> <refentry id="streams.struct-php-stream-wrapper-ops"> <refnamediv> <refname>struct php_stream_wrapper_ops</refname> <refpurpose>Holds member functions for a stream wrapper implementation</refpurpose> </refnamediv> <refsect1> <title>Description</title> <programlisting role="c"> <![CDATA[ typedef struct _php_stream_wrapper_ops { /* open/create a wrapped stream */ php_stream *(*stream_opener)(php_stream_wrapper *wrapper, char *filename, char *mode, int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC); /* close/destroy a wrapped stream */ int (*stream_closer)(php_stream_wrapper *wrapper, php_stream *stream TSRMLS_DC); /* stat a wrapped stream */ int (*stream_stat)(php_stream_wrapper *wrapper, php_stream *stream, php_stream_statbuf *ssb TSR$ /* stat a URL */ int (*url_stat)(php_stream_wrapper *wrapper, char *url, php_stream_statbuf *ssb TSRMLS_DC); /* open a "directory" stream */ php_stream *(*dir_opener)(php_stream_wrapper *wrapper, char *filename, char *mode, int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC); const char *label; /* Delete/Unlink a file */ int (*unlink)(php_stream_wrapper *wrapper, char *url, int options, php_stream_context *context TSRMLS_DC); } php_stream_wrapper_ops; ]]> </programlisting> </refsect1> </refentry> <refentry id="streams.struct-php-stream-filter"> <refnamediv> <refname>struct php_stream_filter</refname> <refpurpose>Holds filter properties and pointer to operations</refpurpose> </refnamediv> <refsect1> <title>Description</title> <programlisting role="c"> <![CDATA[ struct _php_stream_filter { php_stream_filter_ops *fops; void *abstract; /* for use by filter implementation */ php_stream_filter *next; php_stream_filter *prev; int is_persistent; /* link into stream and chain */ php_stream_filter_chain *chain; /* buffered buckets */ php_stream_bucket_brigade buffer; } php_stream_filter; ]]> </programlisting> </refsect1> </refentry> <refentry id="streams.struct-php-stream-filter-ops"> <refnamediv> <refname>struct php_stream_filter_ops</refname> <refpurpose>Holds member functions for a stream filter implementation</refpurpose> </refnamediv> <refsect1> <title>Description</title> <programlisting role="c"> <![CDATA[ typedef struct _php_stream_filter_ops { php_stream_filter_status_t (*filter)( php_stream *stream, php_stream_filter *thisfilter, php_stream_bucket_brigade *buckets_in, php_stream_bucket_brigade *buckets_out, size_t *bytes_consumed, int flags TSRMLS_DC); void (*dtor)(php_stream_filter *thisfilter TSRMLS_DC); const char *label; } php_stream_filter_ops; ]]> </programlisting> </refsect1> </refentry> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/zendapi/api-macros.xml?r=1.1&p=1 Index: phpdoc/en/internals/zendapi/api-macros.xml +++ phpdoc/en/internals/zendapi/api-macros.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <!-- $Revision: 1.1 $ --> <sect1 id="zend.api-macros"> <title>API Macros</title> <para>A set of macros was introduced into Zend's API that simplify access to <envar>zval</envar> containers (see <xref linkend='tab.api-macros'/>).</para> <table id="tab.api-macros"> <title>API Macros for Accessing <envar>zval</envar> Containers</title> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="*"/> <colspec colnum="2" colname="col2" colwidth="*"/> <tbody> <row> <entry colname="col1">Macro</entry> <entry colname="col2">Refers to</entry> </row> <row> <entry colname="col1"><literal>Z_LVAL(zval)</literal></entry> <entry colname="col2"><envar>(zval).value.lval</envar></entry> </row> <row> <entry colname="col1"><literal>Z_DVAL(zval)</literal></entry> <entry colname="col2"><envar>(zval).value.dval</envar></entry> </row> <row> <entry colname="col1"><literal>Z_STRVAL(zval)</literal></entry> <entry colname="col2"><envar>(zval).value.str.val</envar></entry> </row> <row> <entry colname="col1"><literal>Z_STRLEN(zval)</literal></entry> <entry colname="col2"><envar>(zval).value.str.len</envar></entry> </row> <row> <entry colname="col1"><literal>Z_ARRVAL(zval)</literal></entry> <entry colname="col2"><envar>(zval).value.ht</envar></entry> </row> <row> <entry colname="col1"><literal>Z_LVAL_P(zval)</literal></entry> <entry colname="col2"><envar>(*zval).value.lval</envar></entry> </row> <row> <entry colname="col1"><literal>Z_DVAL_P(zval)</literal></entry> <entry colname="col2"><envar>(*zval).value.dval</envar></entry> </row> <row> <entry colname="col1"><literal>Z_STRVAL_P(zval_p)</literal></entry> <entry colname="col2"><envar>(*zval).value.str.val</envar></entry> </row> <row> <entry colname="col1"><literal>Z_STRLEN_P(zval_p)</literal></entry> <entry colname="col2"><envar>(*zval).value.str.len</envar></entry> </row> <row> <entry colname="col1"><literal>Z_ARRVAL_P(zval_p)</literal></entry> <entry colname="col2"><envar>(*zval).value.ht</envar></entry> </row> <row> <entry colname="col1"><literal>Z_LVAL_PP(zval_pp)</literal></entry> <entry colname="col2"><envar>(**zval).value.lval</envar></entry> </row> <row> <entry colname="col1"><literal>Z_DVAL_PP(zval_pp)</literal></entry> <entry colname="col2"><envar>(**zval).value.dval</envar></entry> </row> <row> <entry colname="col1"><literal>Z_STRVAL_PP(zval_pp)</literal></entry> <entry colname="col2"><envar>(**zval).value.str.val</envar></entry> </row> <row> <entry colname="col1"><literal>Z_STRLEN_PP(zval_pp)</literal></entry> <entry colname="col2"><envar>(**zval).value.str.len</envar></entry> </row> <row> <entry colname="col1"><literal>Z_ARRVAL_PP(zval_pp)</literal></entry> <entry colname="col2"><envar>(**zval).value.ht</envar></entry> </row> </tbody> </tgroup> </table> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/zendapi/arguments.xml?r=1.1&p=1 Index: phpdoc/en/internals/zendapi/arguments.xml +++ phpdoc/en/internals/zendapi/arguments.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <!-- $Revision: 1.1 $ --> <sect1 id="zend.arguments"> <title>Accepting Arguments</title> <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. </para> <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. </para> <sect2 id="zend.arguments.count"> <title>Determining the Number of Arguments</title> <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 <literal>ZEND_NUM_ARGS</literal> 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, <envar>ht</envar>, which is passed in the <literal>INTERNAL_FUNCTION_PARAMETERS</literal> list. As <envar>ht</envar> itself now contains the number of arguments that have been passed to the function, <literal>ZEND_NUM_ARGS</literal> has been stripped down to a dummy macro (see its definition in <filename>zend_API.h</filename>). But it's still good practice to use it, to remain compatible with future changes in the call interface. <emphasis>Note:</emphasis> The old PHP equivalent of this macro is <literal>ARG_COUNT</literal>. </para> <para> The following code checks for the correct number of arguments: <programlisting> if(ZEND_NUM_ARGS() != 2) WRONG_PARAM_COUNT; </programlisting> 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 <literal>WRONG_PARAM_COUNT</literal>, which can be used to generate a standard error message (see <xref linkend='fig.wrong-param-count'/>). </para> <figure id='fig.wrong-param-count'> <title><literal>WRONG_PARAM_COUNT</literal> in action.</title> <graphic fileref="figures/zend.03-wrong-parameter-count.png"/> </figure> <para> This macro prints a default error message and then returns to the caller. Its definition can also be found in <filename>zend_API.h</filename> and looks like this: <programlisting> ZEND_API void wrong_param_count(void); #define WRONG_PARAM_COUNT { wrong_param_count(); return; } </programlisting> As you can see, it calls an internal function named <function>wrong_param_count</function> that's responsible for printing the warning. For details on generating customized error messages, see the later section "Printing Information." </para> </sect2> <sect2 id="zend.arguments.retrieval"> <title>Retrieving Arguments</title> <note> <title> New parameter parsing API </title> <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 . </para> </note> <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 parameteres, 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. </para> <para> The prototype for parameter parsing function looks like this: <programlisting> int zend_parse_parameters(int num_args TSRMLS_DC, char *type_spec, ...); </programlisting> The first argument to this function is supposed to be the number of actual parameters passed to your function, so <literal>ZEND_NUM_ARGS()</literal> can be used for that. The second parameter should always be <literal>TSRMLS_CC</literal> 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. </para> <para> <function>zend_parse_parameters</function> 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. </para> <para> If the parameters could be obtained successfully and there were no errors during type conversion, the function will return <literal>SUCCESS</literal>, otherwise it will return <literal>FAILURE</literal>. 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. </para> <para> Here are some sample error messages: <screen> Warning - ini_get_all() requires at most 1 parameter, 2 given Warning - wddx_deserialize() expects parameter 1 to be string, array given </screen> Of course each error message is accompanied by the filename and line number on which it occurs. </para> <para> Here is the full list of type specifiers: <itemizedlist> <listitem> <para><literal>l - </literal>long</para> </listitem> <listitem> <para><literal>d - </literal>double</para> </listitem> <listitem> <para><literal>s - </literal>string (with possible null bytes) and its length</para> </listitem> <listitem> <para><literal>b - </literal>boolean</para> </listitem> <listitem> <para><literal>r - </literal>resource, stored in <literal>zval*</literal></para> </listitem> <listitem> <para><literal>a - </literal>array, stored in <literal>zval*</literal></para> </listitem> <listitem> <para><literal>o - </literal>object (of any class), stored in <literal>zval*</literal></para> </listitem> <listitem> <para><literal>O - </literal>object (of class specified by class entry), stored in <literal>zval*</literal></para> </listitem> <listitem> <para><literal>z - </literal>the actual <literal>zval*</literal></para> </listitem> </itemizedlist> The following characters also have a meaning in the specifier string: <itemizedlist> <listitem> <para> <literal>| - </literal>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. </para> </listitem> <listitem> <para> <literal>/ - </literal>the parsing function will call <function>SEPARATE_ZVAL_IF_NOT_REF</function> on the parameter it follows, to provide a copy of the parameter, unless it's a reference. </para> </listitem> <listitem> <para> <literal>! - </literal>the parameter it follows can be of specified type or <literal>NULL</literal> (only applies to a, o, O, r, and z). If <literal>NULL</literal> value is passed by the user, the storage pointer will be set to <literal>NULL</literal>. </para> </listitem> </itemizedlist> </para> <para> The best way to illustrate the usage of this function is through examples: <programlisting> <![CDATA[ /* 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; } ]]> </programlisting> </para> <para> Note that in the last example we pass 3 for the number of received parameters, instead of <function>ZEND_NUM_ARGS</function>. 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 <function>zend_get_parameters_array_ex</function> to obtain them. </para> <para> The parsing function has an extended version that allows for an additional flags argument that controls its actions. <programlisting> int zend_parse_parameters_ex(int flags, int num_args TSRMLS_DC, char *type_spec, ...); </programlisting> </para> <para> The only flag you can pass currently is <literal>ZEND_PARSE_PARAMS_QUIET</literal>, 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. </para> <para> For example, here is how you would get either a set of three longs or a string: <programlisting> <![CDATA[ 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; }]]> </programlisting> </para> <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. </para> </sect2> <sect2 id="zend.arguments.deprecated-retrieval"> <title>Old way of retrieving arguments (deprecated)</title> <note> <title> Deprecated parameter parsing API </title> <para> This API is deprecated and superseded by the new ZEND parameter parsing API. </para> </note> <para> After having checked the number of arguments, you need to get access to the arguments themselves. This is done with the help of <function>zend_get_parameters_ex</function>: <programlisting> <![CDATA[ zval **parameter; if(zend_get_parameters_ex(1, &parameter) != SUCCESS) WRONG_PARAM_COUNT; ]]> </programlisting> All arguments are stored in a <envar>zval</envar> container, which needs to be pointed to <emphasis>twice</emphasis>. The snippet above tries to retrieve one argument and make it available to us via the <envar>parameter</envar> pointer. </para> <para> <function>zend_get_parameters_ex</function> 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 <envar>zval</envar>s. (Confusing, isn't it?) All these pointers are required because Zend works internally with <envar>**zval</envar>; to adjust a local <envar>**zval</envar> in our function,<function>zend_get_parameters_ex</function> requires a pointer to it. </para> <para> The return value of <function>zend_get_parameters_ex</function> can either be <literal>SUCCESS</literal> or <literal>FAILURE</literal>, 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 <literal>WRONG_PARAM_COUNT</literal>. </para> <para> To retrieve more than one argument, you can use a similar snippet: <programlisting> <![CDATA[ zval **param1, **param2, **param3, **param4; if(zend_get_parameters_ex(4, &param1, &param2, &param3, &param4) != SUCCESS) WRONG_PARAM_COUNT; ]]> </programlisting> </para> <para> <function>zend_get_parameters_ex</function> 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 <function>zend_get_parameters_ex</function>, you won't get an error but will get the first three parameters instead. Subsequent calls of <function>zend_get_parameters_ex</function> won't retrieve the remaining arguments, but will get the same arguments again. </para> </sect2> <sect2 id="zend.arguments.variable"> <title>Dealing with a Variable Number of Arguments/Optional Parameters</title> <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 <function>zend_get_parameters_ex</function> for every possible number of arguments, which is often unsatisfying. </para> <para> For this case, you can use the function <function>zend_get_parameters_array_ex</function>, which accepts the number of parameters to retrieve and an array in which to store them: <programlisting> <![CDATA[ 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; ]]> </programlisting> First, the number of arguments is checked to make sure that it's in the accepted range. After that, <function>zend_get_parameters_array_ex</function> is used to fill <envar>parameter_array</envar> with valid pointers to the argument values. </para> <para> A very clever implementation of this can be found in the code handling PHP's <function>fsockopen</function> located in <filename>ext/standard/fsock.c</filename>, as shown in <xref linkend='example.fsockopen'/>. Don't worry if you don't know all the functions used in this source yet; we'll get to them shortly. </para> <example id='example.fsockopen'> <title>PHP's implementation of variable arguments in fsockopen().</title> <programlisting> <![CDATA[ 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); ]]> </programlisting> </example> <para> <function>fsockopen</function> 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 <literal>switch()</literal> statement to deal with all arguments. The <literal>switch()</literal> 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 <literal>break</literal> keyword in all stages. After having processed the last case, it exits the <literal>switch()</literal> statement and does the minimal argument processing needed if the function is invoked with only two arguments. </para> <para> This multiple-stage type of processing, similar to a stairway, allows convenient processing of a variable number of arguments. </para> </sect2> <sect2 id="zend.arguments.access"> <title>Accessing Arguments</title> <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. </para> <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 <xref linkend='tab.arg-conv'/>). </para> <para> <emphasis>Note:</emphasis> All conversion functions expect a <envar>**zval</envar> as parameter. </para> <table id='tab.arg-conv'> <title>Argument Conversion Functions</title> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="1.02*"/> <colspec colnum="2" colname="col2" colwidth="1.00*"/> <tbody> <row> <entry colname="col1">Function</entry> <entry colname="col2">Description</entry> </row> <row> <entry colname="col1"><function>convert_to_boolean_ex</function></entry> <entry colname="col2"> Forces conversion to a Boolean type. Boolean values remain untouched. Longs, doubles, and strings containing <literal>0</literal> as well as NULL values will result in Boolean <literal>0</literal> (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 <literal>1</literal> (TRUE). </entry> </row> <row> <entry colname="col1"><function>convert_to_long_ex</function></entry> <entry colname="col2"> 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 <literal>0</literal>. Arrays and objects are converted to <literal>0</literal> if empty, <literal>1</literal> otherwise. </entry> </row> <row> <entry colname="col1"><function>convert_to_double_ex</function></entry> <entry colname="col2"> 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 <literal>0.0</literal>. Arrays and objects are converted to <literal>0.0</literal> if empty, <literal>1.0</literal> otherwise. </entry> </row> <row> <entry colname="col1"><function>convert_to_string_ex</function></entry> <entry colname="col2"> Forces conversion to a string. Strings remain untouched. NULL values are converted to an empty string. Booleans containing TRUE are converted to <literal>"1"</literal>, otherwise resulting in an empty string. Longs and doubles are converted to their corresponding string representation. Arrays are converted to the string <literal>"Array"</literal> and objects to the string <literal>"Object"</literal>. </entry> </row> <row> <entry colname="col1"><literal>convert_to_array_ex(value)</literal></entry> <entry colname="col2"> 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 <literal>0</literal>. </entry> </row> <row> <entry colname="col1"><literal>convert_to_object_ex(value)</literal></entry> <entry colname="col2"> 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 <literal>scalar</literal> , having the corresponding source value as content. </entry> </row> <row> <entry colname="col1"><literal>convert_to_null_ex(value)</literal></entry> <entry colname="col2">Forces the type to become a NULL value, meaning empty.</entry> </row> </tbody> </tgroup> </table> <note> <para> You can find a demonstration of the behavior in <filename>cross_conversion.php</filename> on the accompanying CD-ROM. <xref linkend='fig.cross-convert'/> shows the output. </para> </note> <figure id='fig.cross-convert'> <title>Cross-conversion behavior of PHP.</title> <graphic fileref="figures/zend.04-cross-converter.png"/> </figure> <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, <literal>0</literal> for numeric values, <literal>FALSE</literal> for Booleans) to ensure a defined state. </para> <para> Following is a quote from the sample module discussed previously, which makes use of the conversion functions: <programlisting> <![CDATA[ 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)); ]]> </programlisting> 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 <envar>zval</envar> type, whose definition is shown in <xref linkend='example.zval-typedef'/>. </para> <example id='example.zval-typedef'> <title>PHP/Zend <envar>zval</envar> type definition.</title> <programlisting> <![CDATA[ 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; }; ]]> </programlisting> </example> <para> Actually, <envar>pval</envar> (defined in <filename>php.h</filename>) is only an alias of <envar>zval</envar> (defined in <filename>zend.h</filename>), which in turn refers to <envar>_zval_struct</envar>. This is a most interesting structure. <envar>_zval_struct</envar> is the "master" structure, containing the value structure, type, and reference information. The substructure <envar>zvalue_value</envar> 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 <xref linkend='tab.struct-zval'/>, <xref linkend='tab.struct-zvalue-value'/> and <xref linkend='tab.ztype-constants'/>. </para> <table id='tab.struct-zval'> <title>Zend <envar>zval</envar> Structure</title> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="1.00*"/> <colspec colnum="2" colname="col2" colwidth="1.66*"/> <tbody> <row> <entry colname="col1">Entry</entry> <entry colname="col2">Description</entry> </row> <row> <entry colname="col1"><envar>value</envar></entry> <entry colname="col2"> Union containing this variable's contents. See <xref linkend='tab.struct-zvalue-value'/> for a description. </entry> </row> <row> <entry colname="col1"><envar>type</envar></entry> <entry colname="col2"> Contains this variable's type. For a list of available types, see <xref linkend='tab.ztype-constants'/>. </entry> </row> <row> <entry colname="col1"><envar>is_ref</envar></entry> <entry colname="col2"> 0 means that this variable is not a reference; 1 means that this variable is a reference to another variable. </entry> </row> <row> <entry colname="col1"><envar>refcount</envar></entry> <entry colname="col2"> 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. </entry> </row> </tbody> </tgroup> </table> <table id='tab.struct-zvalue-value'> <title>Zend <envar>zvalue_value</envar> Structure</title> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="1.00*"/> <colspec colnum="2" colname="col2" colwidth="1.66*"/> <tbody> <row> <entry colname="col1">Entry</entry> <entry colname="col2">Description</entry> </row> <row> <entry colname="col1"><envar>lval</envar></entry> <entry colname="col2">Use this property if the variable is of the type <literal>IS_LONG</literal>, <literal>IS_BOOLEAN</literal>, or <literal>IS_RESOURCE</literal>.</entry> </row> <row> <entry colname="col1"><envar>dval</envar></entry> <entry colname="col2">Use this property if the variable is of the type <literal>IS_DOUBLE</literal>.</entry> </row> <row> <entry colname="col1"><envar>str</envar></entry> <entry colname="col2"> This structure can be used to access variables of the type <literal>IS_STRING</literal>. The member <envar>len</envar> contains the string length; the member <envar>val</envar> points to the string itself. Zend uses C strings; thus, the string length contains a trailing <literal>0x00</literal>.</entry> </row> <row> <entry colname="col1"><envar>ht</envar></entry> <entry colname="col2">This entry points to the variable's hash table entry if the variable is an array.</entry> </row> <row> <entry colname="col1"><envar>obj</envar></entry> <entry colname="col2">Use this property if the variable is of the type <literal>IS_OBJECT</literal>.</entry> </row> </tbody> </tgroup> </table> <table id='tab.ztype-constants'> <title>Zend Variable Type Constants</title> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="1.00*"/> <colspec colnum="2" colname="col2" colwidth="1.65*"/> <tbody> <row> <entry colname="col1">Constant</entry> <entry colname="col2">Description</entry> </row> <row> <entry colname="col1"><literal>IS_NULL</literal></entry> <entry colname="col2">Denotes a NULL (empty) value.</entry> </row> <row> <entry colname="col1"><literal>IS_LONG</literal></entry> <entry colname="col2">A long (integer) value.</entry> </row> <row> <entry colname="col1"><literal>IS_DOUBLE</literal></entry> <entry colname="col2">A double (floating point) value.</entry> </row> <row> <entry colname="col1"><literal>IS_STRING</literal></entry> <entry colname="col2">A string.</entry> </row> <row> <entry colname="col1"><literal>IS_ARRAY</literal></entry> <entry colname="col2">Denotes an array.</entry> </row> <row> <entry colname="col1"><literal>IS_OBJECT</literal></entry> <entry colname="col2">An object.</entry> </row> <row> <entry colname="col1"><literal>IS_BOOL</literal></entry> <entry colname="col2">A Boolean value.</entry> </row> <row> <entry colname="col1"><literal>IS_RESOURCE</literal></entry> <entry colname="col2">A resource (for a discussion of resources, see the appropriate section below).</entry> </row> <row> <entry colname="col1"><literal>IS_CONSTANT</literal></entry> <entry colname="col2">A constant (defined) value.</entry> </row> </tbody> </tgroup> </table> <para> To access a long you access <envar>zval.value.lval</envar>, to access a double you use <envar>zval.value.dval</envar>, and so on. Because all values are stored in a union, trying to access data with incorrect union members results in meaningless output. </para> <para> Accessing arrays and objects is a bit more complicated and is discussed later. </para> </sect2> <sect2 id="zend.arguments.by-reference"> <title>Dealing with Arguments Passed by Reference</title> <para> If your function accepts arguments passed by reference that you intend to modify, you need to take some precautions. </para> <para> What we didn't say yet is that under the circumstances presented so far, you don't have write access to any <envar>zval</envar> containers designating function parameters that have been passed to you. Of course, you can change any <envar>zval</envar> containers that you created within your function, but you mustn't change any <envar>zval</envar>s that refer to Zend-internal data! </para> <para> We've only discussed the so-called <function>*_ex</function> API so far. You may have noticed that the API functions we've used are called <function>zend_get_parameters_ex</function> instead of <function>zend_get_parameters</function>, <function>convert_to_long_ex</function> instead of <function>convert_to_long</function>, etc. The <function>*_ex</function> 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. </para> <para> Because Zend works internally with references, different variables may reference the same value. Write access to a <envar>zval</envar> container requires this container to contain an isolated value, meaning a value that's not referenced by any other containers. If a <envar>zval</envar> container were referenced by other containers and you changed the referenced <envar>zval</envar>, you would automatically change the contents of the other containers referencing this <envar>zval</envar> (because they'd simply point to the changed value and thus change their own value as well). </para> <para> <function>zend_get_parameters_ex</function> doesn't care about this situation, but simply returns a pointer to the desired <envar>zval</envar> containers, whether they consist of references or not. Its corresponding function in the traditional API, <function>zend_get_parameters</function>, immediately checks for referenced values. If it finds a reference, it creates a new, isolated <envar>zval</envar> container; copies the referenced data into this newly allocated space; and then returns a pointer to the new, isolated value. </para> <para> This action is called <emphasis>zval separation</emphasis> (or pval separation). Because the <function>*_ex</function> API doesn't perform zval separation, it's considerably faster, while at the same time disabling write access. </para> <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 <envar>$parameter</envar> is being passed as an isolated value, rendering it to a write-safe state: <programlisting> my_function(&amp;$parameter); </programlisting> </para> <para> But this <emphasis>is not</emphasis> the case with regular parameters! All other parameters that are not passed by reference are in a read-only state. </para> <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 <literal>PZVAL_IS_REF</literal>. This macro accepts a <literal>zval*</literal> to check if it is a reference or not. Examples are given in in <xref linkend='example.pass-by-ref'/>. </para> <example id='example.pass-by-ref'> <title>Testing for referenced parameter passing.</title> <programlisting> <![CDATA[ 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); ]]> </programlisting> <graphic fileref="figures/zend.05-reference-test.png"/> </example> </sect2> <sect2 id="zend.arguments.write-safety"> <title>Assuring Write Safety for Other Parameters</title> <para> You might run into a situation in which you need write access to a parameter that's retrieved with <function>zend_get_parameters_ex</function> but not passed by reference. For this case, you can use the macro <literal>SEPARATE_ZVAL</literal>, which does a zval separation on the provided container. The newly generated <envar>zval</envar> 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: <programlisting> <![CDATA[ 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 */ ]]> </programlisting> <literal>SEPARATE_ZVAL</literal> uses <function>emalloc</function> to allocate the new <envar>zval</envar> 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. </para> <para> <emphasis>Note:</emphasis> As you can easily work around the lack of write access in the "traditional" API (with <function>zend_get_parameters</function> and so on), this API seems to be obsolete, and is not discussed further in this chapter. </para> </sect2> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/zendapi/build.xml?r=1.1&p=1 Index: phpdoc/en/internals/zendapi/build.xml +++ phpdoc/en/internals/zendapi/build.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <!-- $Revision: 1.1 $ --> <sect1 id="zend.build"> <title>PHP's Automatic Build System</title> <para> PHP 4 features an automatic build system that's very flexible. All modules reside in a subdirectory of the <filename>ext</filename> directory. In addition to its own sources, each module consists of a config.m4 file, for extension configuration. (for example, see <ulink url="http://www.gnu.org/software/m4/manual/m4.html">http://www.gnu.org/software/m4/manual/m4.html</ulink>) </para> <para> All these stub files are generated automatically, along with <filename>.cvsignore</filename>, by a little shell script named <filename>ext_skel</filename> that resides in the <filename>ext</filename> 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. </para> <para> Step by step, the process looks like this: <screen> :~/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. </screen> This instruction creates the aforementioned files. To include the new module in the automatic configuration and build process, you have to run <filename>buildconf</filename>, which regenerates the <filename>configure</filename> script by searching through the <filename>ext</filename> directory and including all found <filename>config.m4</filename> files. </para> <para> The default <filename>config.m4</filename> shown in <xref linkend='example.config.m4'/> is a bit more complex: </para> <example id='example.config.m4'> <title>The default <filename>config.m4</filename>.</title> <programlisting> dnl $Id: build.xml,v 1.1 2005/08/21 16:27:06 goba Exp $ 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 </programlisting> </example> <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. </para> <para> <emphasis>Note:</emphasis> Everything prefixed with <literal>dnl</literal> is treated as a comment and is not parsed. </para> <para> The <filename>config.m4</filename> file is responsible for parsing the command-line options passed to <filename>configure</filename> at configuration time. This means that it has to check for required external files and do similar configuration and setup tasks. </para> <para> The default file creates two configuration directives in the <filename>configure</filename> script: <literal>--with-my_module</literal> and <literal>--enable-my_module</literal>. Use the first option when referring external files (such as the <literal>--with-apache</literal> 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 <literal>--enable-my_module</literal>, you should remove support for <literal>--with-my_module</literal>, and vice versa. </para> <para> By default, the <filename>config.m4</filename> file created by <filename>ext_skel</filename> accepts both directives and automatically enables your extension. Enabling the extension is done by using the <literal>PHP_EXTENSION</literal> macro. To change the default behavior to include your module into the PHP binary when desired by the user (by explicitly specifying <literal>--enable-my_module</literal> or <literal>--with-my_module</literal>), change the test for <literal>$PHP_MY_MODULE</literal> to <literal>== "yes"</literal>: <programlisting>if test "$PHP_MY_MODULE" == "yes"; then dnl Action.. PHP_EXTENSION(my_module, $ext_shared) fi</programlisting>This would require you to use <literal>--enable-my_module</literal> each time when reconfiguring and recompiling PHP. </para> <para> <emphasis>Note:</emphasis> Be sure to run <filename>buildconf</filename> every time you change <filename>config.m4</filename>! </para> <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. </para> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/zendapi/calling-user-functions.xml?r=1.1&p=1 Index: phpdoc/en/internals/zendapi/calling-user-functions.xml +++ phpdoc/en/internals/zendapi/calling-user-functions.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <!-- $Revision: 1.1 $ --> <sect1 id="zend.calling-user-functions"> <title>Calling User Functions</title> <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. </para> <para> User functions can be called with the function <function>call_user_function_ex</function>. 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. </para> <programlisting> 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); </programlisting> <para> Note that you don't have to specify both <envar>function_table</envar> and <envar>object</envar>; either will do. If you want to call a method, you have to supply the object that contains this method, in which case <function>call_user_function</function>automatically sets the function table to this object's function table. Otherwise, you only need to specify <envar>function_table</envar> and can set <envar>object</envar> to <literal>NULL</literal>. </para> <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 <literal>CG</literal>. To introduce the compiler globals to your function, call the macro <literal>TSRMLS_FETCH</literal> once. </para> <para> The function name is specified in a <envar>zval</envar> 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 <envar>zval</envar> containers again. Thus, you only have to pass your arguments through to this function. This <envar>zval</envar> must be of type <literal>IS_STRING</literal>. </para> <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 <function>zval_dtor</function>) afterward! </para> <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 <literal>0</literal>. If set to <literal>1</literal>, the function consumes less memory but fails if any of the parameters need separation. </para> <para> <xref linkend='example.call-user-func'/> 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. </para> <example id='example.call-user-func'> <title>Calling user functions.</title> <programlisting> zval **function_name; zval *retval; if((ZEND_NUM_ARGS() != 1) || (zend_get_parameters_ex(1, &amp;function_name) != SUCCESS)) { WRONG_PARAM_COUNT; } if((*function_name)-&gt;type != IS_STRING) { zend_error(E_ERROR, "Function requires string argument"); } TSRMSLS_FETCH(); if(call_user_function_ex(CG(function_table), NULL, *function_name, &amp;retval, 0, NULL, 0) != SUCCESS) { zend_error(E_ERROR, "Function call failed"); } zend_printf("We have %i as type&lt;br&gt;", retval-&gt;type); *return_value = *retval; zval_copy_ctor(return_value); zval_ptr_dtor(&amp;retval); </programlisting> </example> <para/> <programlisting> &lt;?php dl("call_userland.so"); function test_function() { print("We are in the test function!&lt;br&gt;"); return("hello"); } $return_value = call_userland("test_function"); print("Return value: \"$return_value\"&lt;br&gt;"); ?&gt; </programlisting> <graphic fileref="figures/zend.10-userland.png"/> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/zendapi/configuration-macros.xml?r=1.1&p=1 Index: phpdoc/en/internals/zendapi/configuration-macros.xml +++ phpdoc/en/internals/zendapi/configuration-macros.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <!-- $Revision: 1.1 $ --> <sect1 id="zend.configuration-macros"> <title>Reference: Some Configuration Macros</title> <sect2 id="zend.configuration-macros.config-m4"> <title><filename>config.m4</filename></title> <para> The file <filename>config.m4</filename> is processed by <filename>buildconf</filename> 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 <xref linkend='tab.m4-macros'/>. </para> <table id='tab.m4-macros'> <title>M4 Macros for <filename>config.m4</filename></title> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="1.63*"/> <colspec colnum="2" colname="col2" colwidth="1.00*"/> <tbody> <row> <entry colname="col1">Macro</entry> <entry colname="col2">Description</entry> </row> <row> <entry colname="col1"><literal>AC_MSG_CHECKING(message)</literal></entry> <entry colname="col2">Prints a "checking &lt;message&gt;" text during <filename>configure</filename>.</entry> </row> <row> <entry colname="col1"><literal>AC_MSG_RESULT(value)</literal></entry> <entry colname="col2">Gives the result to <literal>AC_MSG_CHECKING</literal>; should specify either <literal>yes</literal> or <literal>no</literal> as <envar>value</envar>.</entry> </row> <row> <entry colname="col1"><literal>AC_MSG_ERROR(message)</literal></entry> <entry colname="col2">Prints <envar>message</envar> as error message during <filename>configure</filename> and aborts the script.</entry> </row> <row> <entry colname="col1"><literal>AC_DEFINE(name,value,description)</literal></entry> <entry colname="col2">Adds <literal>#define</literal> to <filename>php_config.h</filename> with the value of <envar>value</envar> and a comment that says <envar>description</envar> (this is useful for conditional compilation of your module).</entry> </row> <row> <entry colname="col1"><literal>AC_ADD_INCLUDE(path)</literal></entry> <entry colname="col2">Adds a compiler include path; for example, used if the module needs to add search paths for header files.</entry> </row> <row> <entry colname="col1"><literal>AC_ADD_LIBRARY_WITH_PATH(libraryname,librarypath)</literal></entry> <entry colname="col2">Specifies an additional library to link.</entry> </row> <row> <entry colname="col1"><literal>AC_ARG_WITH(modulename,description,unconditionaltest,conditionaltest)</literal></entry> <entry colname="col2">Quite a powerful macro, adding the module with <envar>description</envar> to the <filename>configure --help</filename> output. PHP checks whether the option <literal>--with-&lt;modulename&gt;</literal> is given to the <filename>configure</filename> script. If so, it runs the script <literal>unconditionaltest</literal> (for example, <literal>--with-myext=yes</literal>), in which case the value of the option is contained in the variable <envar>$withval</envar>. Otherwise, it executes <literal>conditionaltest</literal>. </entry> </row> <row> <entry colname="col1"><literal>PHP_EXTENSION(modulename, [shared])</literal></entry> <entry colname="col2">This macro is a <emphasis>must</emphasis> 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 <literal>COMPILE_DL_&lt;modulename&gt;</literal>.</entry> </row> </tbody> </tgroup> </table> </sect2> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/zendapi/copy-constructor.xml?r=1.1&p=1 Index: phpdoc/en/internals/zendapi/copy-constructor.xml +++ phpdoc/en/internals/zendapi/copy-constructor.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <!-- $Revision: 1.1 $ --> <sect1 id="zend.copy-constructor"> <title>Duplicating Variable Contents: The Copy Constructor</title> <para> Sooner or later, you may need to assign the contents of one <envar>zval</envar> container to another. This is easier said than done, since the <envar>zval</envar> 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 <envar>zval</envar> to another, you avoid duplicating the hash table entries, using only a reference to them (at most). </para> <para> To copy this complex kind of data, use the <emphasis>copy constructor</emphasis>. 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). </para> <para> <emphasis>Overloading</emphasis> 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). </para> <para> This same form of "extended copying" is also necessary for PHP's <envar>zval</envar> 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. </para> <para> Zend ships with such a function, called <function>zend_copy_ctor</function> (the previous PHP equivalent was <function>pval_copy_constructor</function>). </para> <para> A most useful demonstration is a function that accepts a complex type as argument, modifies it, and then returns the argument: </para> <programlisting> zval *parameter; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &amp;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); </programlisting> <para> The first part of the function is plain-vanilla argument retrieval. After the (left out) modifications, however, it gets interesting: The container of <envar>parameter</envar> is assigned to the (predefined) <envar>return_value</envar> 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 <literal>FAILURE</literal> on failure and <literal>SUCCESS</literal> on success. </para> <para> If you omit the call to the copy constructor in this example, both <envar>parameter</envar> and <envar>return_value</envar> would point to the same internal data, meaning that <envar>return_value</envar> would be an illegal additional reference to the same data structures. Whenever changes occurred in the data that <envar>parameter</envar> points to, <envar>return_value</envar> might be affected. Thus, in order to create separate copies, the copy constructor must be used. </para> <para> The copy constructor's counterpart in the Zend API, the destructor <function>zval_dtor</function>, does the opposite of the constructor. </para> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/zendapi/creating.xml?r=1.1&p=1 Index: phpdoc/en/internals/zendapi/creating.xml +++ phpdoc/en/internals/zendapi/creating.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <!-- $Revision: 1.1 $ --> <sect1 id="zend.creating"> <title>Creating Extensions</title> <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. <xref linkend='example.simple'/> shows the source. </para> <example id='example.simple'> <title>A simple extension.</title> <programlisting role="C"> /* 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", &amp;parameter) == FAILURE) { return; } RETURN_LONG(parameter); } </programlisting> </example> <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.) </para> <note> <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. </para> </note> <sect2 id="zend.creating.compiling"> <title>Compiling Modules</title> <para> There are basically two ways to compile modules: <itemizedlist> <listitem> <para> Use the provided "make" mechanism in the <filename>ext</filename> directory, which also allows building of dynamic loadable modules. </para> </listitem> <listitem> <para>Compile the sources manually.</para> </listitem> </itemizedlist> 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. </para> <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. </para> <formalpara> <title>Compiling Using Make</title> <para> To compile the sample sources using the standard mechanism, copy all their subdirectories to the <filename>ext</filename> directory of your PHP source tree. Then run <filename>buildconf</filename>, which will create an updated <filename>configure</filename> 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. </para> </formalpara> <para> After you run <filename>buildconf</filename>, <filename>configure --help</filename> shows the following additional modules: </para> <screen> --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 </screen> <para> The module shown earlier in <xref linkend='example.simple'/> can be enabled with <literal>--enable-first_module</literal> or <literal>--enable-first_module=yes</literal>. </para> <formalpara> <title>Compiling Manually</title> <para> To compile your modules manually, you need the following commands: <informaltable> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="1.00*"/> <colspec colnum="2" colname="col2" colwidth="3.94*"/> <tbody> <row> <entry colname="col1">Action</entry> <entry colname="col2">Command</entry> </row> <row> <entry colname="col1">Compiling</entry> <entry colname="col2">cc -fpic -DCOMPILE_DL=1 -I/usr/local/include -I. -I.. -I../Zend -c -o <filename>&lt;your_object_file&gt;</filename> <filename>&lt;your_c_file&gt;</filename></entry> </row> <row> <entry colname="col1">Linking</entry> <entry colname="col2">cc -shared -L/usr/local/lib -rdynamic -o <filename>&lt;your_module_file&gt;</filename> <filename>&lt;your_object_file(s)&gt;</filename></entry> </row> </tbody> </tgroup> </informaltable> The command to compile the module simply instructs the compiler to generate position-independent code (<literal>-fpic</literal> shouldn't be omitted) and additionally defines the constant <literal>COMPILE_DL</literal> 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. </para> </formalpara> <para> <emphasis>Note:</emphasis> All include paths in the example are relative to the directory <filename>ext</filename>. If you're compiling from another directory, change the pathnames accordingly. Required items are the PHP directory, the <filename>Zend</filename> directory, and (if necessary), the directory in which your module resides. </para> <para> The link command is also a plain vanilla command instructing linkage as a dynamic module. </para> <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). </para> <para> <emphasis>Note:</emphasis> 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.) </para> </sect2> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/zendapi/index.xml?r=1.1&p=1 Index: phpdoc/en/internals/zendapi/index.xml +++ phpdoc/en/internals/zendapi/index.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <!-- $Revision: 1.1 $ --> <chapter id="zend"> <title>&ZendAPI;</title> &internals.zendapi.intro; &internals.zendapi.overview; &internals.zendapi.possibilities; &internals.zendapi.layout; &internals.zendapi.build; &internals.zendapi.creating; &internals.zendapi.using; &internals.zendapi.troubleshooting; &internals.zendapi.structure; &internals.zendapi.arguments; &internals.zendapi.variables; &internals.zendapi.copy-constructor; &internals.zendapi.returning; &internals.zendapi.printing; &internals.zendapi.startup-and-shutdown; &internals.zendapi.calling-user-functions; &internals.zendapi.ini-file-support; &internals.zendapi.where-to-go; &internals.zendapi.configuration-macros; &internals.zendapi.api-macros; </chapter> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/zendapi/ini-file-support.xml?r=1.1&p=1 Index: phpdoc/en/internals/zendapi/ini-file-support.xml +++ phpdoc/en/internals/zendapi/ini-file-support.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <!-- $Id: ini-file-support.xml,v 1.1 2005/08/21 16:27:06 goba Exp $ --> <sect1 id="zend.ini-file-support"> <title>Initialization File Support</title> <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. </para> <para> To create an .ini section in your own module, use the macros <literal>PHP_INI_BEGIN()</literal> to mark the beginning of such a section and <literal>PHP_INI_END()</literal> to mark its end. In between you can use <literal>PHP_INI_ENTRY()</literal> to create entries. <programlisting> 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() </programlisting> The <literal>PHP_INI_ENTRY()</literal> 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. </para> <para> The permissions are grouped into three sections:<literal>PHP_INI_SYSTEM</literal> allows a change only directly in the <filename>php.ini</filename> file; <literal>PHP_INI_USER</literal> allows a change to be overridden by a user at runtime using additional configuration files, such as <filename>.htaccess</filename>; and <literal>PHP_INI_ALL</literal> allows changes to be made without restrictions. There's also a fourth level, <literal>PHP_INI_PERDIR</literal>, for which we couldn't verify its behavior yet. </para> <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 <literal>PHP_INI_MH</literal> macro: <programlisting> 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); } </programlisting> The new value is given to the change handler as string in the variable <envar>new_value</envar>. When looking at the definition of <literal>PHP_INI_MH</literal>, you actually have a few parameters to use: <programlisting> #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) </programlisting> All these definitions can be found in <filename>php_ini.h</filename>. 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 <literal>PHP_INI_ENTRY1</literal> (allowing one additional argument), <literal>PHP_INI_ENTRY2</literal> (allowing two additional arguments), and <literal>PHP_INI_ENTRY3</literal> (allowing three additional arguments). </para> <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. </para> <para> Access to initialization entries can also be handled with the macros shown in <xref linkend='table.ini-macros'/>. </para> <table id='table.ini-macros'> <title>Macros to Access Initialization Entries in PHP</title> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="1.00*"/> <colspec colnum="2" colname="col2" colwidth="1.66*"/> <tbody> <row> <entry colname="col1">Macro</entry> <entry colname="col2">Description</entry> </row> <row> <entry colname="col1"><literal>INI_INT(name)</literal></entry> <entry colname="col2">Returns the current value of entry <literal>name</literal> as integer (long).</entry> </row> <row> <entry colname="col1"><literal>INI_FLT(name)</literal></entry> <entry colname="col2">Returns the current value of entry <literal>name</literal> as float (double).</entry> </row> <row> <entry colname="col1"><literal>INI_STR(name)</literal></entry> <entry colname="col2">Returns the current value of entry <literal>name</literal> as string. <emphasis>Note:</emphasis> This string is not duplicated, but instead points to internal data. Further access requires duplication to local memory.</entry> </row> <row> <entry colname="col1"><literal>INI_BOOL(name)</literal></entry> <entry colname="col2">Returns the current value of entry <literal>name</literal> as Boolean (defined as <envar>zend_bool</envar>, which currently means <envar>unsigned char</envar>).</entry> </row> <row> <entry colname="col1"><literal>INI_ORIG_INT(name)</literal></entry> <entry colname="col2">Returns the original value of entry <literal>name</literal> as integer (long).</entry> </row> <row> <entry colname="col1"><literal>INI_ORIG_FLT(name)</literal></entry> <entry colname="col2">Returns the original value of entry <literal>name</literal> as float (double).</entry> </row> <row> <entry colname="col1"><literal>INI_ORIG_STR(name)</literal></entry> <entry colname="col2">Returns the original value of entry <literal>name</literal> as string. Note: This string is not duplicated, but instead points to internal data. Further access requires duplication to local memory.</entry> </row> <row> <entry colname="col1"><literal>INI_ORIG_BOOL(name)</literal></entry> <entry colname="col2">Returns the original value of entry <literal>name</literal> as Boolean (defined as <envar>zend_bool</envar>, which currently means <envar>unsigned char</envar>).</entry> </row> </tbody> </tgroup> </table> <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 <literal>REGISTER_INI_ENTRIES()</literal> and <literal>UNREGISTER_INI_ENTRIES()</literal>: <programlisting> ZEND_MINIT_FUNCTION(mymodule) { REGISTER_INI_ENTRIES(); } ZEND_MSHUTDOWN_FUNCTION(mymodule) { UNREGISTER_INI_ENTRIES(); } </programlisting> </para> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/zendapi/intro.xml?r=1.1&p=1 Index: phpdoc/en/internals/zendapi/intro.xml +++ phpdoc/en/internals/zendapi/intro.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <!-- $Revision: 1.1 $ --> <sect1 id="zend.intro"> <title>Introduction</title> <abstract> <para>Those who know don't talk.</para> <para>Those who talk don't know.</para> </abstract> <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. </para> <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. </para> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/zendapi/layout.xml?r=1.1&p=1 Index: phpdoc/en/internals/zendapi/layout.xml +++ phpdoc/en/internals/zendapi/layout.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <!-- $Revision: 1.1 $ --> <sect1 id="zend.layout"> <title>Source Layout</title> <note> <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 <ulink url="http://www.apache.org/">http://www.apache.org/</ulink>) and, of course, with PHP (available at <ulink url="http://www.php.net/">http://www.php.net/</ulink> - does it need to be said?). </para> <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. </para> </note> <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. </para> <!-- <para> After extracting the PHP archive, you'll see a directory layout similar to that in <xref linkend='fig.dir-layout'/>. </para> <figure id='fig.dir-layout'> <title>Main directory layout of the PHP source tree.</title> <graphic fileref="figures/Extending_Zend_1a_Directory_Layout.png"/> </figure> --> <para> The following table describes the contents of the major directories. </para> <informaltable> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="1.00*"/> <colspec colnum="2" colname="col2" colwidth="3.74*"/> <tbody> <row> <entry colname="col1">Directory</entry> <entry colname="col2">Contents</entry> </row> <row> <entry colname="col1"><filename>php-src</filename></entry> <entry colname="col2"> 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. </entry> </row> <row> <entry colname="col1"><filename>php-src/ext</filename></entry> <entry colname="col2"> 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). </entry> </row> <row> <entry colname="col1"><filename>php-src/main</filename></entry> <entry colname="col2"> This directory contains the main php macros and definitions. (important) </entry> </row> <row> <entry colname="col1"><filename>php-src/pear</filename></entry> <entry colname="col2"> Directory for the PHP Extension and Application Repository. This directory contains core PEAR files. </entry> </row> <row> <entry colname="col1"><filename>php-src/sapi</filename></entry> <entry colname="col2"> Contains the code for the different server abstraction layers. </entry> </row> <row> <entry colname="col1"><filename>TSRM</filename></entry> <entry colname="col2"> Location of the "Thread Safe Resource Manager" (TSRM) for Zend and PHP. </entry> </row> <row> <entry colname="col1"><filename>ZendEngine2</filename></entry> <entry colname="col2"> Location of the Zend Engine files; here you'll find all of Zend's API definitions, macros, etc. (important). </entry> </row> </tbody> </tgroup> </informaltable> <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:<itemizedlist> <listitem> <para> <filename>php-src/main/php.h</filename>, located in the main PHP directory. This file contains most of PHP's macro and API definitions. </para> </listitem> <listitem> <para> <filename>php-src/Zend/zend.h</filename>, located in the main Zend directory. This file contains most of Zend's macros and definitions. </para> </listitem> <listitem> <para> <filename>php-src/Zend/zend_API.h</filename>, also located in the Zend directory, which defines Zend's API. </para> </listitem> </itemizedlist> 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. </para> <sect2 id="zend.layout.conventions"> <title>Extension Conventions</title> <para> Zend is built using certain conventions; to avoid breaking its standards, you should follow the rules described in the following sections. </para> </sect2> <sect2 id="zend.layout.macros"> <title>Macros</title> <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 <filename>zend.h</filename> and <filename>zend_API.h</filename>. 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.) </para> </sect2> <sect2 id="zend.layout.memory-management"> <title>Memory Management</title> <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: <informaltable> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="1.00*"/> <colspec colnum="2" colname="col2" colwidth="1.62*"/> <tbody> <row> <entry colname="col1">Function</entry> <entry colname="col2">Description</entry> </row> <row> <entry colname="col1"><function>emalloc</function></entry> <entry colname="col2">Serves as replacement for <function>malloc</function>.</entry> </row> <row> <entry colname="col1"><function>efree</function></entry> <entry colname="col2">Serves as replacement for <function>free</function>.</entry> </row> <row> <entry colname="col1"><function>estrdup</function></entry> <entry colname="col2">Serves as replacement for <function>strdup</function>.</entry> </row> <row> <entry colname="col1"><function>estrndup</function></entry> <entry colname="col2">Serves as replacement for <function>strndup</function>. Faster than <function>estrdup</function> and binary-safe. This is the recommended function to use if you know the string length prior to duplicating it.</entry> </row> <row> <entry colname="col1"><function>ecalloc</function></entry> <entry colname="col2">Serves as replacement for <function>calloc</function>.</entry> </row> <row> <entry colname="col1"><function>erealloc</function></entry> <entry colname="col2">Serves as replacement for <function>realloc</function>.</entry> </row> </tbody> </tgroup> </informaltable> <function>emalloc</function>, <function>estrdup</function>, <function>estrndup</function>, <function>ecalloc</function>, and <function>erealloc</function> allocate internal memory; <function>efree</function> frees these previously allocated blocks. Memory handled by the <function>e*</function> functions is considered local to the current process and is discarded as soon as the script executed by this process is terminated. <warning> <para> To allocate resident memory that survives termination of the current script, you can use <function>malloc</function> and <function>free</function>. This should only be done with extreme care, however, and only in conjunction with demands of the Zend API; otherwise, you risk memory leaks. </para> </warning> 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. </para> </sect2> <sect2 id="zend.layout.dir-and-file"> <title>Directory and File Functions</title> <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. <informaltable> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="*"/> <colspec colnum="2" colname="col2" colwidth="*"/> <tbody> <row> <entry colname="col1">Zend Function</entry> <entry colname="col2">Regular C Function</entry> </row> <row> <entry colname="col1"><function>V_GETCWD</function></entry> <entry colname="col2"><function>getcwd</function></entry> </row> <row> <entry colname="col1"><function>V_FOPEN</function></entry> <entry colname="col2"><function>fopen</function></entry> </row> <row> <entry colname="col1"><function>V_OPEN</function></entry> <entry colname="col2"><function>open</function></entry> </row> <row> <entry colname="col1"><function>V_CHDIR</function></entry> <entry colname="col2"><function>chdir</function></entry> </row> <row> <entry colname="col1"><function>V_GETWD</function></entry> <entry colname="col2"><function>getwd</function></entry> </row> <row> <entry colname="col1"><function>V_CHDIR_FILE</function></entry> <entry colname="col2"> Takes a file path as an argument and changes the current working directory to that file's directory. </entry> </row> <row> <entry colname="col1"><function>V_STAT</function></entry> <entry colname="col2"><function>stat</function></entry> </row> <row> <entry colname="col1"><function>V_LSTAT</function></entry> <entry colname="col2"><function>lstat</function></entry> </row> </tbody> </tgroup> </informaltable></para> </sect2> <sect2 id="zend.layout.string-handling"> <title>String Handling</title> <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 <function>e*</function> 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.) </para> </sect2> <sect2 id="zend.layout.complex-types"> <title>Complex Types</title> <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. </para> <note> <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. </para> </note> </sect2> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/zendapi/overview.xml?r=1.1&p=1 Index: phpdoc/en/internals/zendapi/overview.xml +++ phpdoc/en/internals/zendapi/overview.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <!-- $Revision: 1.1 $ --> <sect1 id="zend.overview"> <title>Overview</title> <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. </para> <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. </para> <sect2 id="zend.overview.whatisit"> <title>What Is Zend? and What Is PHP?</title> <para> The name <emphasis>Zend</emphasis> refers to the language engine, PHP's core. The term <emphasis>PHP</emphasis> 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 (see <xref linkend='fig.internal-struct'/>). To implement a Web script interpreter, you need three parts: <orderedlist> <listitem> <para> The <emphasis>interpreter</emphasis> part analyzes the input code, translates it, and executes it. </para> </listitem> <listitem> <para> The <emphasis>functionality</emphasis> part implements the functionality of the language (its functions, etc.). </para> </listitem> <listitem> <para> The <emphasis>interface</emphasis> part talks to the Web server, etc. </para> </listitem> </orderedlist> 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. <figure id='fig.internal-struct'> <title>The internal structure of PHP.</title> <graphic fileref="figures/zend.01-internal-structure.png"/> </figure> </para> <para> The following sections discuss where PHP can be extended and how it's done. </para> </sect2> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/zendapi/possibilities.xml?r=1.1&p=1 Index: phpdoc/en/internals/zendapi/possibilities.xml +++ phpdoc/en/internals/zendapi/possibilities.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <!-- $Revision: 1.1 $ --> <sect1 id="zend.possibilities"> <title>Extension Possibilities</title> <para> As shown in <xref linkend='fig.internal-struct'/> above, PHP can be extended primarily at three points: external modules, built-in modules, and the Zend engine. The following sections discuss these options. </para> <sect2 id="zend.possibilities.external"> <title>External Modules</title> <para> External modules can be loaded at script runtime using the function <function>dl</function>. 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: <informaltable> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="*"/> <colspec colnum="2" colname="col2" colwidth="*"/> <tbody> <row> <entry colname="col1">Advantages</entry> <entry colname="col2">Disadvantages</entry> </row> <row> <entry colname="col1"> External modules don't require recompiling of PHP. </entry> <entry colname="col2"> The shared objects need to be loaded every time a script is being executed (every hit), which is very slow. </entry> </row> <row> <entry colname="col1"> The size of PHP remains small by "outsourcing" certain functionality. </entry> <entry colname="col2"> External additional files clutter up the disk. </entry> </row> <row> <entry colname="col1"></entry> <entry colname="col2"> Every script that wants to use an external module's functionality has to specifically include a call to <function>dl</function>, or the <literal>extension</literal> tag in <filename>php.ini</filename> needs to be modified (which is not always a suitable solution). </entry> </row> </tbody> </tgroup> </informaltable> 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. </para> <para> Third parties might consider using the <literal>extension</literal> tag in <filename>php.ini</filename> 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. </para> </sect2> <sect2 id="zend.possibilities.builtin"> <title>Built-in Modules</title> <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: <informaltable> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="*"/> <colspec colnum="2" colname="col2" colwidth="*"/> <tbody> <row> <entry colname="col1">Advantages</entry> <entry colname="col2">Disadvantages</entry> </row> <row> <entry colname="col1"> No need to load the module specifically; the functionality is instantly available. </entry> <entry colname="col2"> Changes to built-in modules require recompiling of PHP. </entry> </row> <row> <entry colname="col1"> No external files clutter up the disk; everything resides in the PHP binary. </entry> <entry colname="col2"> The PHP binary grows and consumes more memory. </entry> </row> </tbody> </tgroup> </informaltable> 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. </para> </sect2> <sect2 id="zend.possibilities.engine"> <title>The Zend Engine</title> <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. </para> </sect2> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/zendapi/printing.xml?r=1.1&p=1 Index: phpdoc/en/internals/zendapi/printing.xml +++ phpdoc/en/internals/zendapi/printing.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <!-- $Revision: 1.1 $ --> <sect1 id="zend.printing"> <title>Printing Information</title> <para> Often it's necessary to print messages to the output stream from your module, just as <function>print</function> would be used within a script. PHP offers functions for most generic tasks, such as printing warning messages, generating output for <function>phpinfo</function>, and so on. The following sections provide more details. Examples of these functions can be found on the CD-ROM. </para> <sect2 id="zend.printing.zend-printf"> <title><function>zend_printf</function></title> <para> <function>zend_printf</function> works like the standard <function>printf</function>, except that it prints to Zend's output stream. </para> </sect2> <sect2 id="zend.printing.zend-error"> <title><function>zend_error</function></title> <para> <function>zend_error</function> can be used to generate error messages. This function accepts two arguments; the first is the error type (see <filename>zend_errors.h</filename>), and the second is the error message. <programlisting>zend_error(E_WARNING, "This function has been called with empty arguments");</programlisting><xref linkend='tab.error-messages'/> shows a list of possible values (see <xref linkend='fig.warning-messages'/>). These values are also referred to in <filename>php.ini</filename>. Depending on which error type you choose, your messages will be logged. <table id='tab.error-messages'> <title>Zend's Predefined Error Messages.</title> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="1.00*"/> <colspec colnum="2" colname="col2" colwidth="1.36*"/> <tbody> <row> <entry colname="col1">Error</entry> <entry colname="col2">Description</entry> </row> <row> <entry colname="col1"><literal>E_ERROR</literal></entry> <entry colname="col2"> Signals an error and terminates execution of the script immediately .</entry> </row> <row> <entry colname="col1"><literal>E_WARNING</literal></entry> <entry colname="col2"> Signals a generic warning. Execution continues. </entry> </row> <row> <entry colname="col1"><literal>E_PARSE</literal></entry> <entry colname="col2"> Signals a parser error. Execution continues. </entry> </row> <row> <entry colname="col1"><literal>E_NOTICE</literal></entry> <entry colname="col2"> Signals a notice. Execution continues. Note that by default the display of this type of error messages is turned off in <filename>php.ini</filename>. </entry> </row> <row> <entry colname="col1"><literal>E_CORE_ERROR</literal></entry> <entry colname="col2"> Internal error by the core; shouldn't be used by user-written modules. </entry> </row> <row> <entry colname="col1"><literal>E_COMPILE_ERROR</literal></entry> <entry colname="col2"> Internal error by the compiler; shouldn't be used by user-written modules. </entry> </row> <row> <entry colname="col1"><literal>E_COMPILE_WARNING</literal></entry> <entry colname="col2"> Internal warning by the compiler; shouldn't be used by user-written modules. </entry> </row> </tbody> </tgroup> </table> <figure id='fig.warning-messages'> <title>Display of warning messages in the browser.</title> <graphic fileref="figures/zend.07-warning-messages.png"/> </figure></para> </sect2> <sect2 id="zend.printing.phpinfo"> <title>Including Output in <function>phpinfo</function></title> <para> After creating a real module, you'll want to show information about the module in <function>phpinfo</function> (in addition to the module name, which appears in the module list by default). PHP allows you to create your own section in the <function>phpinfo</function> output with the <literal>ZEND_MINFO()</literal> function. This function should be placed in the module descriptor block (discussed earlier) and is always called whenever a script calls <function>phpinfo</function>. </para> <para> PHP automatically prints a section in <function>phpinfo</function> for you if you specify the <literal>ZEND_MINFO</literal> function, including the module name in the heading. Everything else must be formatted and printed by you. </para> <para> Typically, you can print an HTML table header using <function>php_info_print_table_start</function> and then use the standard functions <function>php_info_print_table_header</function> and <function>php_info_print_table_row</function>. As arguments, both take the number of columns (as integers) and the column contents (as strings). <xref linkend='example.phpinfo'/> shows a source example and its output. To print the table footer, use <function>php_info_print_table_end</function>. </para> <example id='example.phpinfo'> <title> Source code and screenshot for output in <function>phpinfo</function>. </title> <programlisting> 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(); </programlisting> <graphic fileref="figures/zend.08-phpinfo-output.png"/> </example> </sect2> <sect2 id="zend.printing.execution"> <title>Execution Information</title> <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 <function>get_active_function_name</function>. 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 <function>zend_get_executed_filename</function>. This function accesses the executor globals, which are passed to it using the <literal>TSRMLS_C</literal> macro. The executor globals are automatically available to every function that's called directly by Zend (they're part of the <literal>INTERNAL_FUNCTION_PARAMETERS</literal> 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 <literal>TSRMLS_FETCH()</literal> once in that function; this will introduce them to your local scope. </para> <para> Finally, the line number currently being executed can be retrieved using the function <function>zend_get_executed_lineno</function>. This function also requires the executor globals as arguments. For examples of these functions, see <xref linkend='example.exec-info'/>. </para> <example id='example.exec-info'> <title>Printing execution information.</title> <programlisting> 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)); </programlisting> <graphic fileref="figures/zend.09-execution-info.png"/> </example> </sect2> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/zendapi/returning.xml?r=1.1&p=1 Index: phpdoc/en/internals/zendapi/returning.xml +++ phpdoc/en/internals/zendapi/returning.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <!-- $Revision: 1.1 $ --> <sect1 id="zend.returning"> <title>Returning Values</title> <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 <envar>return_value</envar> variable, which is passed to your functions as argument. The <envar>return_value</envar> argument consists of a <envar>zval</envar> 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 <literal>MAKE_STD_ZVAL</literal> on it. Instead, you can access its members directly. </para> <para> To make returning values from functions easier and to prevent hassles with accessing the internal structures of the <envar>zval</envar> container, a set of predefined macros is available (as usual). These macros automatically set the correspondent type and value, as described in <xref linkend='tab.return'/> and <xref linkend='tab.retval'/>. </para> <note> <para> The macros in <xref linkend='tab.return'/> automatically <emphasis>return</emphasis> from your function, those in <xref linkend='tab.retval'/> only <emphasis>set</emphasis> the return value; they don't return from your function. </para> </note> <table id='tab.return'> <title>Predefined Macros for Returning Values from a Function</title> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="*"/> <colspec colnum="2" colname="col2" colwidth="*"/> <tbody> <row> <entry colname="col1">Macro</entry> <entry colname="col2">Description</entry> </row> <row> <entry colname="col1"><literal>RETURN_RESOURCE(resource)</literal></entry> <entry colname="col2">Returns a resource.</entry> </row> <row> <entry colname="col1"><literal>RETURN_BOOL(bool)</literal></entry> <entry colname="col2">Returns a Boolean.</entry> </row> <row> <entry colname="col1"><literal>RETURN_NULL()</literal></entry> <entry colname="col2">Returns nothing (a NULL value).</entry> </row> <row> <entry colname="col1"><literal>RETURN_LONG(long)</literal></entry> <entry colname="col2">Returns a long.</entry> </row> <row> <entry colname="col1"><literal>RETURN_DOUBLE(double)</literal></entry> <entry colname="col2">Returns a double.</entry> </row> <row> <entry colname="col1"> <literal>RETURN_STRING(string, duplicate)</literal> </entry> <entry colname="col2"> Returns a string. The <envar>duplicate</envar> flag indicates whether the string should be duplicated using <function>estrdup</function>. </entry> </row> <row> <entry colname="col1"> <literal>RETURN_STRINGL(string, length, duplicate)</literal> </entry> <entry colname="col2"> Returns a string of the specified length; otherwise, behaves like <literal>RETURN_STRING</literal>. This macro is faster and binary-safe, however. </entry> </row> <row> <entry colname="col1"><literal>RETURN_EMPTY_STRING()</literal></entry> <entry colname="col2">Returns an empty string.</entry> </row> <row> <entry colname="col1"><literal>RETURN_FALSE</literal></entry> <entry colname="col2">Returns Boolean false.</entry> </row> <row> <entry colname="col1"><literal>RETURN_TRUE</literal></entry> <entry colname="col2">Returns Boolean true.</entry> </row> </tbody> </tgroup> </table> <table id='tab.retval'> <title>Predefined Macros for Setting the Return Value of a Function</title> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="*"/> <colspec colnum="2" colname="col2" colwidth="*"/> <tbody> <row> <entry colname="col1">Macro</entry> <entry colname="col2">Description</entry> </row> <row> <entry colname="col1"><literal>RETVAL_RESOURCE(resource)</literal></entry> <entry colname="col2">Sets the return value to the specified resource.</entry> </row> <row> <entry colname="col1"><literal>RETVAL_BOOL(bool)</literal></entry> <entry colname="col2">Sets the return value to the specified Boolean value.</entry> </row> <row> <entry colname="col1"><literal>RETVAL_NULL</literal></entry> <entry colname="col2">Sets the return value to NULL.</entry> </row> <row> <entry colname="col1"><literal>RETVAL_LONG(long)</literal></entry> <entry colname="col2"> Sets the return value to the specified long. </entry> </row> <row> <entry colname="col1"><literal>RETVAL_DOUBLE(double)</literal></entry> <entry colname="col2"> Sets the return value to the specified double. </entry> </row> <row> <entry colname="col1"> <literal>RETVAL_STRING(string, duplicate)</literal> </entry> <entry colname="col2"> Sets the return value to the specified string and duplicates it to Zend internal memory if desired (see also <literal>RETURN_STRING</literal>). </entry> </row> <row> <entry colname="col1"> <literal>RETVAL_STRINGL(string, length, duplicate)</literal> </entry> <entry colname="col2"> Sets the return value to the specified string and forces the length to become <envar>length</envar> (see also <literal>RETVAL_STRING</literal>). This macro is faster and binary-safe, and should be used whenever the string length is known. </entry> </row> <row> <entry colname="col1"> <literal>RETVAL_EMPTY_STRING</literal> </entry> <entry colname="col2"> Sets the return value to an empty string. </entry> </row> <row> <entry colname="col1"><literal>RETVAL_FALSE</literal></entry> <entry colname="col2"> Sets the return value to Boolean false. </entry> </row> <row> <entry colname="col1"><literal>RETVAL_TRUE</literal></entry> <entry colname="col2"> Sets the return value to Boolean true. </entry> </row> </tbody> </tgroup> </table> <para> Complex types such as arrays and objects can be returned by using <function>array_init</function> and <function>object_init</function>, as well as the corresponding hash functions on <envar>return_value</envar>. Since these types cannot be constructed of trivial information, there are no predefined macros for them. </para> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/zendapi/startup-and-shutdown.xml?r=1.1&p=1 Index: phpdoc/en/internals/zendapi/startup-and-shutdown.xml +++ phpdoc/en/internals/zendapi/startup-and-shutdown.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <!-- $Revision: 1.1 $ --> <sect1 id="zend.startup-and-shutdown"> <title>Startup and Shutdown Functions</title> <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. </para> <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). </para> <para> For dynamic extensions, module and request startup/shutdown events happen at the same time. </para> <para> Declaration and implementation of these functions can be done with macros; see the earlier section "Declaration of the Zend Module Block" for details. </para> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/zendapi/structure.xml?r=1.1&p=1 Index: phpdoc/en/internals/zendapi/structure.xml +++ phpdoc/en/internals/zendapi/structure.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <!-- $Revision: 1.1 $ --> <sect1 id="zend.structure"> <title>Source Discussion</title> <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. </para> <sect2 id="zend.structure.module"> <title>Module Structure</title> <para> All PHP modules follow a common structure: <itemizedlist> <listitem> <para> Header file inclusions (to include all required macros, API definitions, etc.) </para> </listitem> <listitem> <para> C declaration of exported functions (required to declare the Zend function block) </para> </listitem> <listitem> <para>Declaration of the Zend function block</para> </listitem> <listitem> <para>Declaration of the Zend module block</para> </listitem> <listitem> <para>Implementation of <function>get_module</function></para> </listitem> <listitem> <para>Implementation of all exported functions</para> </listitem> </itemizedlist></para> </sect2> <sect2 id="zend.structure.headers"> <title>Header File Inclusions</title> <para> The only header file you really have to include for your modules is <filename>php.h</filename>, located in the PHP directory. This file makes all macros and API definitions required to build new modules available to your code. </para> <para> <emphasis>Tip:</emphasis> 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 <filename>php.h</filename>. If you created your module using <literal>ext_skel</literal> you already have such a header file prepared. </para> </sect2> <sect2 id="zend.structure.exporting-functions"> <title>Declaring Exported Functions</title> <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: <programlisting> ZEND_FUNCTION ( my_function ); </programlisting> </para> <para> <literal>ZEND_FUNCTION</literal> declares a new C function that complies with Zend's internal API. This means that the function is of type <literal>void</literal> and accepts <literal>INTERNAL_FUNCTION_PARAMETERS</literal> (another macro) as parameters. Additionally, it prefixes the function name with <literal>zif</literal>. The immediately expanded version of the above definitions would look like this: <programlisting> void zif_my_function ( INTERNAL_FUNCTION_PARAMETERS ); </programlisting> Expanding <literal>INTERNAL_FUNCTION_PARAMETERS</literal> results in the following: <programlisting> void zif_my_function( int ht , zval * return_value , zval * this_ptr , int return_value_used , zend_executor_globals * executor_globals ); </programlisting> </para> <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 <envar>zval</envar> and <envar>pval</envar> are identical. <envar>zval</envar> is Zend's definition; <envar>pval</envar> is PHP's definition (actually, <envar>pval</envar> is an alias for <envar>zval</envar> now). As the macro <literal>INTERNAL_FUNCTION_PARAMETERS</literal> is a Zend macro, the above declaration contains <envar>zval</envar>. When writing code, you should always use <envar>zval</envar> to conform to the new Zend API. </para> <para> The parameter list of this declaration is very important; you should keep these parameters in mind (see <xref linkend='tab.parameters'/> for descriptions). <table id='tab.parameters'> <title>Zend's Parameters to Functions Called from PHP</title> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="1.00*"/> <colspec colnum="2" colname="col2" colwidth="1.79*"/> <tbody> <row> <entry colname="col1">Parameter</entry> <entry colname="col2">Description</entry> </row> <row> <entry colname="col1"><envar>ht</envar></entry> <entry colname="col2"> 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. </entry> </row> <row> <entry colname="col1"> <envar>return_value</envar></entry> <entry colname="col2"> 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. </entry> </row> <row> <entry colname="col1"><envar>this_ptr</envar></entry> <entry colname="col2"> 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 <function>getThis</function> to obtain this pointer. </entry> </row> <row> <entry colname="col1"><envar>return_value_used</envar></entry> <entry colname="col2"> This flag indicates whether an eventual return value from this function will actually be used by the calling script. <literal>0</literal> indicates that the return value is not used; <literal>1</literal> 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 <filename>array.c</filename> makes use of this). </entry> </row> <row> <entry colname="col1"><envar>executor_globals</envar></entry> <entry colname="col2"> 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 <literal>TSRMLS_FETCH()</literal>. </entry> </row> </tbody> </tgroup> </table> </para> </sect2> <sect2 id="zend.structure.function-block"> <title>Declaration of the Zend Function Block</title> <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 <envar>zend_function_entry</envar>. 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, <envar>zend_function_entry</envar> is defined as shown in <xref linkend='example.zend-function-entry'/>. </para> <para> <example id='example.zend-function-entry'> <title>Internal declaration of <envar>zend_function_entry</envar>.</title> <programlisting> typedef struct _zend_function_entry { char *fname; void (*handler)(INTERNAL_FUNCTION_PARAMETERS); unsigned char *func_arg_types; } zend_function_entry; </programlisting> <informaltable> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="1.00*"/> <colspec colnum="2" colname="col2" colwidth="1.82*"/> <tbody> <row> <entry colname="col1">Entry</entry> <entry colname="col2">Description</entry> </row> <row> <entry colname="col1"><envar>fname</envar></entry> <entry colname="col2"> Denotes the function name as seen in PHP (for example, <literal>fopen</literal>, <literal>mysql_connect</literal>, or, in our example, <literal>first_module</literal>). </entry> </row> <row> <entry colname="col1"><envar>handler</envar></entry> <entry colname="col2"> Pointer to the C function responsible for handling calls to this function. For example, see the standard macro <literal>INTERNAL_FUNCTION_PARAMETERS</literal> discussed earlier. </entry> </row> <row> <entry colname="col1"><envar>func_arg_types</envar></entry> <entry colname="col2"> Allows you to mark certain parameters so that they're forced to be passed by reference. You usually should set this to NULL. </entry> </row> </tbody> </tgroup> </informaltable> </example> In the example above, the declaration looks like this: <programlisting> zend_function_entry firstmod_functions[] = { ZEND_FE(first_module, NULL) {NULL, NULL, NULL} }; </programlisting> You can see that the last entry in the list always has to be <literal>{NULL, NULL, NULL}</literal>. This marker has to be set for Zend to know when the end of the list of exported functions is reached. </para> <note> <para> You <emphasis>cannot</emphasis> use the predefined macros for the end marker, as these would try to refer to a function named "NULL"! </para> </note> <para> The macro <literal>ZEND_FE</literal> (short for 'Zend Function Entry') simply expands to a structure entry in <envar>zend_function_entry</envar>. Note that these macros introduce a special naming scheme to your functions - your C functions will be prefixed with <literal>zif_</literal>, meaning that <literal>ZEND_FE(first_module)</literal> will refer to a C function <function>zif_first_module</function>. If you want to mix macro usage with hand-coded entries (not a good practice), keep this in mind. </para> <para> Tip: Compilation errors that refer to functions named <function>zif_*</function> relate to functions defined with <literal>ZEND_FE</literal>. </para> <para> <xref linkend='tab.funcdef-macros'/> shows a list of all the macros that you can use to define functions. </para> <table id='tab.funcdef-macros'> <title>Macros for Defining Functions</title> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="1.00*"/> <colspec colnum="2" colname="col2" colwidth="1.08*"/> <tbody> <row> <entry colname="col1">Macro Name</entry> <entry colname="col2">Description</entry> </row> <row> <entry colname="col1"><literal>ZEND_FE(name, arg_types)</literal></entry> <entry colname="col2"> Defines a function entry of the name <envar>name</envar> in <envar>zend_function_entry</envar>. Requires a corresponding C function. <envar>arg_types</envar> needs to be set to <literal>NULL</literal>. This function uses automatic C function name generation by prefixing the PHP function name with <literal>zif_</literal>. For example, <literal>ZEND_FE("first_module", NULL)</literal> introduces a function <function>first_module</function> to PHP and links it to the C function <function>zif_first_module</function>. Use in conjunction with <literal>ZEND_FUNCTION</literal>. </entry> </row> <row> <entry colname="col1"> <literal>ZEND_NAMED_FE(php_name, name, arg_types)</literal> </entry> <entry colname="col2"> Defines a function that will be available to PHP by the name <envar>php_name</envar> and links it to the corresponding C function <envar>name</envar>. <envar>arg_types</envar> needs to be set to <literal>NULL</literal>. Use this function if you don't want the automatic name prefixing introduced by <literal>ZEND_FE</literal>. Use in conjunction with <literal>ZEND_NAMED_FUNCTION</literal>. </entry> </row> <row> <entry colname="col1"> <literal>ZEND_FALIAS(name, alias, arg_types)</literal> </entry> <entry colname="col2"> Defines an alias named <envar>alias</envar> for <envar>name</envar>. <envar>arg_types</envar> needs to be set to <literal>NULL</literal>. Doesn't require a corresponding C function; refers to the alias target instead. </entry> </row> <row> <entry colname="col1"><literal>PHP_FE(name, arg_types)</literal></entry> <entry colname="col2"> Old PHP API equivalent of <literal>ZEND_FE</literal>. </entry> </row> <row> <entry colname="col1"> <literal>PHP_NAMED_FE(runtime_name, name, arg_types)</literal> </entry> <entry colname="col2"> Old PHP API equivalent of <literal>ZEND_NAMED_FE</literal>. </entry> </row> </tbody> </tgroup> </table> <para> <emphasis>Note:</emphasis> You can't use <literal>ZEND_FE</literal> in conjunction with <literal>PHP_FUNCTION</literal>, or <literal>PHP_FE</literal> in conjunction with <literal>ZEND_FUNCTION</literal>. However, it's perfectly legal to mix <literal>ZEND_FE</literal> and <literal>ZEND_FUNCTION</literal> with <literal>PHP_FE</literal> and <literal>PHP_FUNCTION</literal> when staying with the same macro set for each function to be declared. But mixing is <emphasis>not</emphasis> recommended; instead, you're advised to use the <literal>ZEND_*</literal> macros only. </para> </sect2> <sect2 id="zend.structure.module-block"> <title>Declaration of the Zend Module Block</title> <para> This block is stored in the structure <envar>zend_module_entry</envar> and contains all necessary information to describe the contents of this module to Zend. You can see the internal definition of this module in <xref linkend='example.zend-module-entry'/>. </para> <example id='example.zend-module-entry'> <title>Internal declaration of <envar>zend_module_entry</envar>.</title> <programlisting> 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 ] }; </programlisting> <informaltable> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="1.00*"/> <colspec colnum="2" colname="col2" colwidth="1.69*"/> <thead> <row> <entry colname="col1">Entry</entry> <entry colname="col2">Description</entry> </row> </thead> <tbody> <row> <entry colname="col1"> <envar>size</envar>, <envar>zend_api</envar>, <envar>zend_debug</envar> and <envar>zts</envar> </entry> <entry colname="col2"> Usually filled with the <literal>"STANDARD_MODULE_HEADER"</literal>, which fills these four members with the size of the whole zend_module_entry, the <literal>ZEND_MODULE_API_NO</literal>, whether it is a debug build or normal build (<literal>ZEND_DEBUG</literal>) and if ZTS is enabled (<literal>USING_ZTS</literal>). </entry> </row> <row> <entry colname="col1"><envar>name</envar></entry> <entry colname="col2"> Contains the module name (for example, <literal>"File functions"</literal>, <literal>"Socket functions"</literal>, <literal>"Crypt"</literal>, etc.). This name will show up in <function>phpinfo</function>, in the section "Additional Modules." </entry> </row> <row> <entry colname="col1"><envar>functions</envar></entry> <entry colname="col2"> Points to the Zend function block, discussed in the preceding section. </entry> </row> <row> <entry colname="col1"><envar>module_startup_func</envar></entry> <entry colname="col2"> 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 <literal>FAILURE</literal>; otherwise, <literal>SUCCESS</literal>. To mark this field as unused, use <literal>NULL</literal>. To declare a function, use the macro <literal>ZEND_MINIT</literal>. </entry> </row> <row> <entry colname="col1"><envar>module_shutdown_func</envar></entry> <entry colname="col2"> 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 <function>module_startup_func</function>. To indicate a failure during deinitialization, return <literal>FAILURE</literal>; otherwise, <literal>SUCCESS</literal>. To mark this field as unused, use <literal>NULL</literal>. To declare a function, use the macro <literal>ZEND_MSHUTDOWN</literal>. </entry> </row> <row> <entry colname="col1"><envar>request_startup_func</envar></entry> <entry colname="col2"> 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 <literal>FAILURE</literal>; otherwise, <literal>SUCCESS</literal>. <emphasis>Note:</emphasis> 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 <literal>NULL</literal>. To declare a function, use the macro <literal>ZEND_RINIT</literal>. </entry> </row> <row> <entry colname="col1"><envar>request_shutdown_func</envar></entry> <entry colname="col2"> This function is called once after every page request and works as counterpart to <function>request_startup_func</function>. To indicate a failure here, return <literal>FAILURE</literal>; otherwise, <literal>SUCCESS</literal>. <emphasis>Note:</emphasis> 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 <literal>NULL</literal>. To declare a function, use the macro <literal>ZEND_RSHUTDOWN</literal>. </entry> </row> <row> <entry colname="col1"><envar>info_func</envar></entry> <entry colname="col2"> When <function>phpinfo</function> 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 <literal>NULL</literal>. To declare a function, use the macro <literal>ZEND_MINFO</literal>. </entry> </row> <row> <entry colname="col1"><envar>version</envar></entry> <entry colname="col2"> The version of the module. You can use <literal>NO_VERSION_YET</literal> 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): <literal>"2.5-dev"</literal>, <literal>"2.5RC1"</literal>, <literal>"2.5"</literal> or <literal>"2.5pl3"</literal>. </entry> </row> <row> <entry colname="col1">Remaining structure elements</entry> <entry colname="col2"> These are used internally and can be prefilled by using the macro <literal>STANDARD_MODULE_PROPERTIES_EX</literal>. You should not assign any values to them. Use <literal>STANDARD_MODULE_PROPERTIES_EX</literal> only if you use global startup and shutdown functions; otherwise, use <literal>STANDARD_MODULE_PROPERTIES</literal> directly. </entry> </row> </tbody> </tgroup> </informaltable> </example> <para> In our example, this structure is implemented as follows: <programlisting> zend_module_entry firstmod_module_entry = { STANDARD_MODULE_HEADER, "First Module", firstmod_functions, NULL, NULL, NULL, NULL, NULL, NO_VERSION_YET, STANDARD_MODULE_PROPERTIES, }; </programlisting> This is basically the easiest and most minimal set of values you could ever use. The module name is set to <literal>First Module</literal>, then the function list is referenced, after which all startup and shutdown functions are marked as being unused. </para> <para> For reference purposes, you can find a list of the macros involved in declared startup and shutdown functions in <xref linkend='tab.init-shutdown'/>. 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 (<literal>INIT_FUNC_ARGS</literal> and <literal>SHUTDOWN_FUNC_ARGS</literal>), 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. </para> <table id='tab.init-shutdown'> <title>Macros to Declare Startup and Shutdown Functions</title> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="1.00*"/> <colspec colnum="2" colname="col2" colwidth="1.41*"/> <tbody> <row> <entry colname="col1">Macro</entry> <entry colname="col2">Description</entry> </row> <row> <entry colname="col1"><literal>ZEND_MINIT(module)</literal></entry> <entry colname="col2"> Declares a function for module startup. The generated name will be <literal>zend_minit_&lt;module&gt;</literal> (for example, <literal>zend_minit_first_module</literal>). Use in conjunction with <literal>ZEND_MINIT_FUNCTION</literal>. </entry> </row> <row> <entry colname="col1"><literal>ZEND_MSHUTDOWN(module)</literal></entry> <entry colname="col2"> Declares a function for module shutdown. The generated name will be <literal>zend_mshutdown_&lt;module&gt;</literal> (for example, <literal>zend_mshutdown_first_module</literal>). Use in conjunction with <literal>ZEND_MSHUTDOWN_FUNCTION</literal>. </entry> </row> <row> <entry colname="col1"><literal>ZEND_RINIT(module)</literal></entry> <entry colname="col2"> Declares a function for request startup. The generated name will be <literal>zend_rinit_&lt;module&gt;</literal> (for example, <literal>zend_rinit_first_module</literal>). Use in conjunction with <literal>ZEND_RINIT_FUNCTION</literal>. </entry> </row> <row> <entry colname="col1"><literal>ZEND_RSHUTDOWN(module)</literal></entry> <entry colname="col2"> Declares a function for request shutdown. The generated name will be <literal>zend_rshutdown_&lt;module&gt;</literal> (for example, <literal>zend_rshutdown_first_module</literal>). Use in conjunction with <literal>ZEND_RSHUTDOWN_FUNCTION</literal>. </entry> </row> <row> <entry colname="col1"><literal>ZEND_MINFO(module)</literal></entry> <entry colname="col2"> Declares a function for printing module information, used when <function>phpinfo</function> is called. The generated name will be <literal>zend_info_&lt;module&gt;</literal> (for example, <literal>zend_info_first_module</literal>). Use in conjunction with <literal>ZEND_MINFO_FUNCTION</literal>. </entry> </row> </tbody> </tgroup> </table> </sect2> <sect2 id="zend.structure.get-module"> <title>Creation of <function>get_module</function></title> <para> This function is special to all dynamic loadable modules. Take a look at the creation via the <literal>ZEND_GET_MODULE</literal> macro first: </para> <programlisting> #if COMPILE_DL_FIRSTMOD ZEND_GET_MODULE(firstmod) #endif </programlisting> <para> The function implementation is surrounded by a conditional compilation statement. This is needed since the function <function>get_module</function> is only required if your module is built as a dynamic extension. By specifying a definition of <literal>COMPILE_DL_FIRSTMOD</literal> 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 <function>get_module</function> is simply left out. </para> <para> <function>get_module</function> is called by Zend at load time of the module. You can think of it as being invoked by the <function>dl</function> 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. </para> <para> If you don't implement a <function>get_module</function> function in your dynamic loadable module, Zend will compliment you with an error message when trying to access it. </para> </sect2> <sect2 id="zend.structure.implementation"> <title>Implementation of All Exported Functions</title> <para>Implementing the exported functions is the final step. The example function in <literal>first_module</literal> looks like this: <programlisting> ZEND_FUNCTION(first_module) { long parameter; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &amp;parameter) == FAILURE) { return; } RETURN_LONG(parameter); } </programlisting> The function declaration is done using <literal>ZEND_FUNCTION</literal>, which corresponds to <literal>ZEND_FE</literal> in the function entry table (discussed earlier). </para> <para> After the declaration, code for checking and retrieving the function's arguments, argument conversion, and return value generation follows (more on this later). </para> </sect2> <sect2 id="zend.structure.summary"> <title>Summary</title> <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. </para> <para> Now, in the following sections, read on about how to make use of PHP's internals to build powerful extensions. </para> </sect2> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/zendapi/troubleshooting.xml?r=1.1&p=1 Index: phpdoc/en/internals/zendapi/troubleshooting.xml +++ phpdoc/en/internals/zendapi/troubleshooting.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <!-- $Revision: 1.1 $ --> <sect1 id="zend.troubleshooting"> <title>Troubleshooting</title> <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 <filename>ext</filename> directory with the fresh files; this will guarantee a safe compilation environment. If this fails, try manual compilation. </para> <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. </para> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/zendapi/using.xml?r=1.1&p=1 Index: phpdoc/en/internals/zendapi/using.xml +++ phpdoc/en/internals/zendapi/using.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <!-- $Revision: 1.1 $ --> <sect1 id="zend.using"> <title>Using Extensions</title> <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 <filename>first_module.c</filename> as a shared object, your result file should be <filename>first_module.so</filename>. 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 <filename>htdocs</filename> directory and try it with the source in <xref linkend='example.testfile'/>. If you compiled it into the PHP binary, omit the call to <function>dl</function>, as the module's functionality is instantly available to your scripts. <warning> <para> For security reasons, you <emphasis>should not</emphasis> put your dynamic modules into publicly accessible directories. Even though it <emphasis>can</emphasis> be done and it simplifies testing, you should put them into a separate directory in production environments. </para> </warning> </para> <example id='example.testfile'> <title>A test file for first_module.so.</title> <programlisting role='php'> <![CDATA[ <?php // remove next comment if necessary // dl("first_module.so"); $param = 2; $return = first_module($param); print("We sent '$param' and got '$return'"); ?> ]]> </programlisting> </example> <para> Calling this PHP file in your Web browser should give you the output shown in <xref linkend='fig.out-first'/>. <figure id='fig.out-first'> <title>Output of first_module.php.</title> <graphic fileref="figures/zend.02-first-module-output.png"/> </figure> </para> <para> If required, the dynamic loadable module is loaded by calling the <function>dl</function> function. This function looks for the specified shared object, loads it, and makes its functions available to PHP. The module exports the function <function>first_module</function>, which accepts a single parameter, converts it to an integer, and returns the result of the conversion. </para> <para> If you've gotten this far, congratulations! You just built your first extension to PHP. </para> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/zendapi/variables.xml?r=1.1&p=1 Index: phpdoc/en/internals/zendapi/variables.xml +++ phpdoc/en/internals/zendapi/variables.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <!-- $Revision: 1.1 $ --> <sect1 id="zend.variables"> <title>Creating Variables</title> <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. </para> <sect2 id="zend.variables.overview"> <title>Overview</title> <para> To create new variables that can be seen "from the outside" by the executing script, you need to allocate a new <envar>zval</envar> 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: </para> <programlisting> 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 */ </programlisting> <para> The macro <literal>MAKE_STD_ZVAL</literal> allocates a new <envar>zval</envar> container using <literal>ALLOC_ZVAL</literal> and initializes it using <literal>INIT_ZVAL</literal>. As implemented in Zend at the time of this writing, <emphasis>initializing</emphasis> means setting the reference count to <literal>1</literal> and clearing the <envar>is_ref</envar> flag, but this process could be extended later - this is why it's a good idea to keep using <literal>MAKE_STD_ZVAL</literal> instead of only using <literal>ALLOC_ZVAL</literal>. If you want to optimize for speed (and you don't have to explicitly initialize the <envar>zval</envar> container here), you can use <literal>ALLOC_ZVAL</literal>, but this isn't recommended because it doesn't ensure data integrity. </para> <para> <literal>ZEND_SET_SYMBOL</literal> 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 <envar>zval</envar> container). This is the preferred method if speed is not a crucial issue and you'd like to keep memory usage low. </para> <para> Note that <literal>ZEND_SET_SYMBOL</literal> makes use of the Zend executor globals via the macro <literal>EG</literal>. By specifying <literal>EG(active_symbol_table)</literal>, 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. </para> <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 <function>zend_hash_update</function>: <programlisting> 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, &amp;new_variable, sizeof(zval *), NULL ); </programlisting> This is actually the standard method used in most modules. </para> <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: <programlisting> 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(&amp;EG(symbol_table), "new_variable_name", new_variable); </programlisting> The macro <literal>ZEND_SET_SYMBOL</literal> is now being called with a reference to the main, global symbol table by referring <literal>EG(symbol_table)</literal>. </para> <para> <emphasis>Note:</emphasis> The <envar>active_symbol_table</envar> variable is a pointer, but <envar>symbol_table</envar> is not. This is why you have to use <literal>EG(active_symbol_table)</literal> and <literal>&amp;EG(symbol_table)</literal> as parameters to <literal>ZEND_SET_SYMBOL</literal> - it requires a pointer. </para> <para> Similarly, to get a more efficient version, you can hardcode the symbol table update: <programlisting> 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( &amp;EG(symbol_table), "new_variable_name", strlen("new_variable_name") + 1, &amp;new_variable, sizeof(zval *), NULL ); </programlisting> <xref linkend='example.variable-scopes'/> shows a sample source that creates two variables - <envar>local_variable</envar> with a local scope and <envar>global_variable</envar> with a global scope (see Figure 9.7). The full example can be found on the CD-ROM. </para> <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 <literal>global $global_variable;</literal> in the PHP source. </para> <example id='example.variable-scopes'> <title>Creating variables with different scopes.</title> <programlisting> 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(&amp;EG(symbol_table), "global_variable", new_var2); RETURN_NULL(); } </programlisting> <graphic fileref="figures/zend.06-variable-creation.png"/> </example> </sect2> <sect2 id="zend.variables.long"> <title>Longs (Integers)</title> <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 <envar>zval.value</envar> container structure discussed earlier in this chapter, you can see that the long data type is directly contained in the union, namely in the <envar>lval</envar> field. The corresponding <envar>type</envar> value for longs is <literal>IS_LONG</literal> (see <xref linkend='example.create-long'/>). <example id='example.create-long'> <title>Creation of a long.</title> <programlisting> zval *new_long; MAKE_STD_ZVAL(new_long); new_long-&gt;type = IS_LONG; new_long-&gt;value.lval = 10; </programlisting> </example> Alternatively, you can use the macro <literal>ZVAL_LONG</literal>: <programlisting> zval *new_long; MAKE_STD_ZVAL(new_long); ZVAL_LONG(new_long, 10); </programlisting> </para> </sect2> <sect2 id="zend.variables.float"> <title>Doubles (Floats)</title> <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 <envar>zval.value</envar> container is <envar>dval</envar>; the corresponding type is <literal>IS_DOUBLE</literal>. <programlisting> zval *new_double; MAKE_STD_ZVAL(new_double); new_double-&gt;type = IS_DOUBLE; new_double-&gt;value.dval = 3.45; </programlisting> Alternatively, you can use the macro <literal>ZVAL_DOUBLE</literal>: <programlisting> zval *new_double; MAKE_STD_ZVAL(new_double); ZVAL_DOUBLE(new_double, 3.45); </programlisting> </para> </sect2> <sect2 id="zend.variables.string"> <title>Strings</title> <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 <envar>str</envar> in the <envar>zval.value</envar> container. The corresponding type is <literal>IS_STRING</literal>: <programlisting> 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); </programlisting> Note the usage of Zend's <function>estrdup</function> here. Of course, you can also use the predefined macro <literal>ZVAL_STRING</literal>: <programlisting> zval *new_string; char *string_contents = "This is a new string variable"; MAKE_STD_ZVAL(new_string); ZVAL_STRING(new_string, string_contents, 1); </programlisting> <literal>ZVAL_STRING</literal> accepts a third parameter that indicates whether the supplied string contents should be duplicated (using <function>estrdup</function>). Setting this parameter to <literal>1</literal> causes the string to be duplicated; <literal>0</literal> 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. </para> <para> If you want to truncate the string at a certain position or you already know its length, you can use <literal>ZVAL_STRINGL(zval, string, length, duplicate)</literal>, which accepts an explicit string length to be set for the new string. This macro is faster than <literal>ZVAL_STRING</literal> and also binary-safe. </para> <para> To create empty strings, set the string length to <literal>0</literal> and use <literal>empty_string</literal> as contents: <programlisting> new_string-&gt;type = IS_STRING; new_string-&gt;value.str.len = 0; new_string-&gt;value.str.val = empty_string; </programlisting> Of course, there's a macro for this as well (<literal>ZVAL_EMPTY_STRING</literal>): <programlisting> MAKE_STD_ZVAL(new_string); ZVAL_EMPTY_STRING(new_string); </programlisting> </para> </sect2> <sect2 id="zend.variables.boolean"> <title>Booleans</title> <para> Booleans are created just like longs, but have the type <literal>IS_BOOL</literal>. Allowed values in <envar>lval</envar> are <literal>0</literal> and <literal>1</literal>: <programlisting> zval *new_bool; MAKE_STD_ZVAL(new_bool); new_bool-&gt;type = IS_BOOL; new_bool-&gt;value.lval = 1; </programlisting> The corresponding macros for this type are <literal>ZVAL_BOOL</literal> (allowing specification of the value) as well as <literal>ZVAL_TRUE</literal> and <literal>ZVAL_FALSE</literal> (which explicitly set the value to <literal>TRUE</literal> and <literal>FALSE</literal>, respectively). </para> </sect2> <sect2 id="zend.variables.array"> <title>Arrays</title> <para> Arrays are stored using Zend's internal hash tables, which can be accessed using the <function>zend_hash_*</function> API. For every array that you want to create, you need a new hash table handle, which will be stored in the <envar>ht</envar> member of the <envar>zval.value</envar> container. </para> <para> There's a whole API solely for the creation of arrays, which is extremely handy. To start a new array, you call <function>array_init</function>. <programlisting> zval *new_array; MAKE_STD_ZVAL(new_array); array_init(new_array); </programlisting> <function>array_init</function> always returns <literal>SUCCESS</literal>. </para> <para> To add new elements to the array, you can use numerous functions, depending on what you want to do. <xref linkend='tab.api-assoc-arrays'/>, <xref linkend='tab.api-indexed-arrays'/> and <xref linkend='tab.api-indexed-array-2'/> describe these functions. All functions return <literal>FAILURE</literal> on failure and <literal>SUCCESS</literal> on success. </para> <table id='tab.api-assoc-arrays'> <title>Zend's API for Associative Arrays</title> <!-- <programlisting> Note: The functions in this table all operate on the array "array" with the key "key". The key string doesn't have to reside in Zend internal memory; it will be duplicated by the API. </programlisting> --> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="*"/> <colspec colnum="2" colname="col2" colwidth="*"/> <tbody> <row> <entry colname="col1">Function</entry> <entry colname="col2">Description</entry> </row> <row> <entry colname="col1"> <function>add_assoc_long(zval *array, char *key, long n);</function> </entry> <entry colname="col2">Adds an element of type <literal>long</literal>.</entry> </row> <row> <entry colname="col1"> <function>add_assoc_unset(zval *array, char *key);</function></entry> <entry colname="col2">Adds an unset element.</entry> </row> <row> <entry colname="col1"> <function>add_assoc_bool(zval *array, char *key, int b);</function> </entry> <entry colname="col2">Adds a Boolean element.</entry> </row> <row> <entry colname="col1"> <function>add_assoc_resource(zval *array, char *key, int r);</function> </entry> <entry colname="col2">Adds a resource to the array.</entry> </row> <row> <entry colname="col1"> <function>add_assoc_double(zval *array, char *key, double d);</function> </entry> <entry colname="col2">Adds a floating-point value.</entry> </row> <row> <entry colname="col1"> <function>add_assoc_string(zval *array, char *key, char *str, int duplicate);</function> </entry> <entry colname="col2"> Adds a string to the array. The flag <envar>duplicate</envar> specifies whether the string contents have to be copied to Zend internal memory. </entry> </row> <row> <entry colname="col1"> <function> add_assoc_stringl(zval *array, char *key, char *str, uint length, int duplicate); </function> </entry> <entry colname="col2"> Adds a string with the desired length <envar>length</envar> to the array. Otherwise, behaves like <function>add_assoc_string</function>. </entry> </row> <row> <entry colname="col1"><function>add_assoc_zval(zval *array, char *key, zval *value);</function></entry> <entry colname="col2">Adds a zval to the array. Useful for adding other arrays, objects, streams, etc...</entry> </row> </tbody> </tgroup> </table> <table id='tab.api-indexed-arrays'> <title>Zend's API for Indexed Arrays, Part 1</title> <!-- <programlisting> Note: The functions in this table all operate on the array "array" with the index "idx". The index is always an integer. </programlisting> --> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="*"/> <colspec colnum="2" colname="col2" colwidth="*"/> <tbody> <row> <entry colname="col1">Function</entry> <entry colname="col2">Description</entry> </row> <row> <entry colname="col1"><function>add_index_long(zval *array, uint idx, long n);</function></entry> <entry colname="col2">Adds an element of type <literal>long</literal>.</entry> </row> <row> <entry colname="col1"><function>add_index_unset(zval *array, uint idx);</function></entry> <entry colname="col2">Adds an unset element.</entry> </row> <row> <entry colname="col1"><function>add_index_bool(zval *array, uint idx, int b);</function></entry> <entry colname="col2">Adds a Boolean element.</entry> </row> <row> <entry colname="col1"><function>add_index_resource(zval *array, uint idx, int r);</function></entry> <entry colname="col2">Adds a resource to the array.</entry> </row> <row> <entry colname="col1"><function>add_index_double(zval *array, uint idx, double d);</function></entry> <entry colname="col2">Adds a floating-point value.</entry> </row> <row> <entry colname="col1"><function>add_index_string(zval *array, uint idx, char *str, int duplicate);</function></entry> <entry colname="col2">Adds a string to the array. The flag <envar>duplicate</envar> specifies whether the string contents have to be copied to Zend internal memory.</entry> </row> <row> <entry colname="col1"><function>add_index_stringl(zval *array, uint idx, char *str, uint length, int duplicate);</function></entry> <entry colname="col2">Adds a string with the desired length <envar>length</envar> to the array. This function is faster and binary-safe. Otherwise, behaves like <function>add_index_string()</function>.</entry> </row> <row> <entry colname="col1"><function>add_index_zval(zval *array, uint idx, zval *value);</function></entry> <entry colname="col2">Adds a zval to the array. Useful for adding other arrays, objects, streams, etc...</entry> </row> </tbody> </tgroup> </table> <table id='tab.api-indexed-array-2'> <title>Zend's API for Indexed Arrays, Part 2</title> <!-- <programlisting> Note: The functions in this table all operate on the array "array". These functions automatically generate a new index based on the highest index found in the array. </programlisting> --> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="*"/> <colspec colnum="2" colname="col2" colwidth="*"/> <tbody> <row> <entry colname="col1">Function</entry> <entry colname="col2">Description</entry> </row> <row> <entry colname="col1"><function>add_next_index_long(zval *array, long n);</function></entry> <entry colname="col2">Adds an element of type <literal>long</literal>.</entry> </row> <row> <entry colname="col1"><function>add_next_index_unset(zval *array);</function></entry> <entry colname="col2">Adds an unset element.</entry> </row> <row> <entry colname="col1"><function>add_next_index_bool(zval *array, int b);</function></entry> <entry colname="col2">Adds a Boolean element.</entry> </row> <row> <entry colname="col1"><function>add_next_index_resource(zval *array, int r);</function></entry> <entry colname="col2">Adds a resource to the array.</entry> </row> <row> <entry colname="col1"><function>add_next_index_double(zval *array, double d);</function></entry> <entry colname="col2">Adds a floating-point value.</entry> </row> <row> <entry colname="col1"><function>add_next_index_string(zval *array, char *str, int duplicate);</function></entry> <entry colname="col2">Adds a string to the array. The flag <envar>duplicate</envar> specifies whether the string contents have to be copied to Zend internal memory.</entry> </row> <row> <entry colname="col1"><function>add_next_index_stringl(zval *array, char *str, uint length, int duplicate);</function></entry> <entry colname="col2">Adds a string with the desired length <envar>length</envar> to the array. This function is faster and binary-safe. Otherwise, behaves like <function>add_index_string()</function>.</entry> </row> <row> <entry colname="col1"><function>add_next_index_zval(zval *array, zval *value);</function></entry> <entry colname="col2">Adds a zval to the array. Useful for adding other arrays, objects, streams, etc...</entry> </row> </tbody> </tgroup> </table> <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 <envar>zval</envar> container allocated that you want to insert into an array. This is done using <function>zend_hash_update()</function> for associative arrays (see <xref linkend='example.array-add-assoc'/>) and <function>zend_hash_index_update</function> for indexed arrays (see <xref linkend='example.array-add-indexed'/>): <example id='example.array-add-assoc'> <title>Adding an element to an associative array.</title> <programlisting> 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 *)&amp;new_element, sizeof(zval *), NULL) == FAILURE) { // do error handling here } </programlisting> </example> <example id='example.array-add-indexed'> <title>Adding an element to an indexed array.</title> <programlisting> 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 *)&amp;new_element, sizeof(zval *), NULL) == FAILURE) { // do error handling here } </programlisting> </example> </para> <para> To emulate the functionality of <function>add_next_index_*</function>, you can use this: </para> <programlisting> zend_hash_next_index_insert(ht, zval **new_element, sizeof(zval *), NULL) </programlisting> <para> <emphasis>Note:</emphasis> To return arrays from a function, use <function>array_init</function> and all following actions on the predefined variable <envar>return_value</envar> (given as argument to your exported function; see the earlier discussion of the call interface). You do not have to use <literal>MAKE_STD_ZVAL</literal> on this. </para> <para> <emphasis>Tip:</emphasis> To avoid having to write <literal>new_array-&gt;value.ht</literal> every time, you can use <literal>HASH_OF(new_array)</literal>, which is also recommended for compatibility and style reasons. </para> </sect2> <sect2 id="zend.variables.object"> <title>Objects</title> <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. </para> <para> To initialize an object, you use the function <function>object_init</function>: <programlisting> zval *new_object; MAKE_STD_ZVAL(new_object); if(object_init(new_object) != SUCCESS) { // do error handling here } </programlisting> You can use the functions described in <xref linkend='tab.object-creation'/> to add members to your object. </para> <table id='tab.object-creation'> <title>Zend's API for Object Creation</title> <!-- <programlisting> Note: All functions in this table work on the object "object" with the key "key". The key forms the member name, so the resulting member can be accessed via $object-&gt;key. </programlisting> --> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="1.24*"/> <colspec colnum="2" colname="col2" colwidth="1.00*"/> <tbody> <row> <entry colname="col1">Function</entry> <entry colname="col2">Description</entry> </row> <row> <entry colname="col1"><function>add_property_long(zval *object, char *key, long l);</function></entry> <entry colname="col2">Adds a long to the object.</entry> </row> <row> <entry colname="col1"><function>add_property_unset(zval *object, char *key);</function></entry> <entry colname="col2">Adds an unset property to the object.</entry> </row> <row> <entry colname="col1"><function>add_property_bool(zval *object, char *key, int b);</function></entry> <entry colname="col2">Adds a Boolean to the object.</entry> </row> <row> <entry colname="col1"><function>add_property_resource(zval *object, char *key, long r);</function></entry> <entry colname="col2">Adds a resource to the object.</entry> </row> <row> <entry colname="col1"><function>add_property_double(zval *object, char *key, double d);</function></entry> <entry colname="col2">Adds a double to the object.</entry> </row> <row> <entry colname="col1"><function>add_property_string(zval *object, char *key, char *str, int duplicate);</function></entry> <entry colname="col2">Adds a string to the object.</entry> </row> <row> <entry colname="col1"><function>add_property_stringl(zval *object, char *key, char *str, uint length, int duplicate);</function></entry> <entry colname="col2">Adds a string of the specified length to the object. This function is faster than <function>add_property_string</function> and also binary-safe.</entry> </row> <row> <entry colname="col1"> <function>add_property_zval(zval *obect, char *key, zval *container):</function> </entry> <entry colname="col2"> Adds a <literal>zval</literal> 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. </entry> </row> </tbody> </tgroup> </table> </sect2> <sect2 id="zend.variables.resource"> <title>Resources</title> <para> Resources are a special kind of data type in PHP. The term <emphasis>resources</emphasis> 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. </para> <para> For example, resources are used to store database links and file descriptors. The <emphasis>de facto</emphasis> standard implementation can be found in the MySQL module, but other modules such as the Oracle module also make use of resources. <note> <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. </para> </note> </para> <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 <emphasis role="strong">resource type handle</emphasis> 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. </para> <para> The Zend function to register your resource handler is defined as: <programlisting> ZEND_API int zend_register_list_destructors_ex(rsrc_dtor_func_t ld, rsrc_dtor_func_t pld, char *type_name, int module_number); </programlisting> </para> <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 <literal>NULL</literal>. </para> <para> <function>zend_register_list_destructors_ex</function> accepts the following parameters: <informaltable> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="1.00*"/> <colspec colnum="2" colname="col2" colwidth="5.00*"/> <tbody> <row> <entry colname="col1"><literal>ld</literal></entry> <entry colname="col2">Normal resource destruction handler callback</entry> </row> <row> <entry colname="col1"><literal>pld</literal></entry> <entry colname="col2">Pesistent resource destruction handler callback</entry> </row> <row> <entry colname="col1"><literal>type_name</literal></entry> <entry colname="col2">A string specifying the name of your resource. It's always a good thing to specify an unique name within PHP for the resource type so when the user for example calls <literal>var_dump($resource);</literal> he also gets the name of the resource.</entry> </row> <row> <entry colname="col1"><literal>module_number</literal></entry> <entry colname="col2">The <literal>module_number</literal> is automatically available in your <literal>PHP_MINIT_FUNCTION</literal> function and therefore you just pass it over.</entry> </row> </tbody> </tgroup> </informaltable> The return value is an unique integer ID for your <emphasis role="strong">resource type</emphasis>. </para> <para> The resource destruction handler (either normal or persistent resources) has the following prototype: <programlisting>void resource_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC);</programlisting> The passed <literal>rsrc</literal> is a pointer to the following structure: <programlisting> typedef struct _zend_rsrc_list_entry { void *ptr; int type; int refcount; } zend_rsrc_list_entry; </programlisting> The member <literal>void *ptr</literal> is the actual pointer to your resource. </para> <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: <programlisting> typedef struct { int resource_link; int resource_type; } my_resource; </programlisting> Our resource destruction handler is probably going to look something like this: <programlisting> 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); } </programlisting> <note> <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 <emphasis role="strong">before</emphasis> freeing the resource itself! </para> </note> </para> <para> Now that we have defined <orderedlist> <listitem><para>what our resource is and</para></listitem> <listitem><para>our resource destruction handler</para></listitem> </orderedlist> we can go on and do the rest of the steps: <orderedlist> <listitem><para>create a global variable within the extension holding the resource ID so it can be accessed from every function which needs it</para></listitem> <listitem><para>define the resource name</para></listitem> <listitem><para>write the resource destruction handler</para></listitem> <listitem><para>and finally register the handler</para></listitem> </orderedlist> <programlisting> // 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. } </programlisting> </para> <para> To actually register a new resource you use can either use the <function>zend_register_resource</function> function or the <function>ZEND_REGISTER_RESOURE</function> 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: <programlisting> int ZEND_REGISTER_RESOURCE(zval *rsrc_result, void *rsrc_pointer, int rsrc_type); </programlisting> <informaltable> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="1.00*"/> <colspec colnum="2" colname="col2" colwidth="5.00*"/> <tbody> <row> <entry colname="col1"><literal>rsrc_result</literal></entry> <entry colname="col2">This is an already initialized <literal>zval *</literal> container.</entry> </row> <row> <entry colname="col1"><literal>rsrc_pointer</literal></entry> <entry colname="col2">Your resource pointer you want to store.</entry> </row> <row> <entry colname="col1"><literal>rsrc_type</literal></entry> <entry colname="col2">The type which you received when you registered the resource destruction handler. If you followed the naming scheme this would be <literal>le_myresource</literal>.</entry> </row> </tbody> </tgroup> </informaltable> The return value is an unique integer identifier for that resource. </para> <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 <literal>zval *</literal> container: <programlisting> 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; </programlisting> The returned <literal>rsrc_id</literal> uniquly identifies the newly registered resource. You can use the macro <literal>RETURN_RESOURE</literal> to return it to the user: <programlisting> RETURN_RESOURCE(rsrc_id)</programlisting> <note><para>It is common practice that if you want to return the resource immidiately to the user you specify the <literal>return_value</literal> as the <literal>zval *</literal> container. </para> </note> </para> <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. </para> <para> Now that the user got his resource, at some point he is passing it back to one of your functions. The <envar>value.lval</envar> inside the <literal>zval *</literal> container contains the key to your resource and thus can be used to fetch the resource with the following macro: <literal>ZEND_FETCH_RESOURCE</literal>: <programlisting> ZEND_FETCH_RESOURCE(rsrc, rsrc_type, rsrc_id, default_rsrc_id, resource_type_name, resource_type) </programlisting> <informaltable> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="1.00*"/> <colspec colnum="2" colname="col2" colwidth="5.00*"/> <tbody> <row> <entry colname="col1"><literal>rsrc</literal></entry> <entry colname="col2">This is your pointer which will point to your previously registered resource.</entry> </row> <row> <entry colname="col1"><literal>rsrc_type</literal></entry> <entry colname="col2">This is the typecast argument for your pointer, e.g. <literal>myresource *</literal>.</entry> </row> <row> <entry colname="col1"><literal>rsrc_id</literal></entry> <entry colname="col2">This is the address of the <literal>zval *</literal>container the user passed to your function, e.g. <literal>&amp;z_resource</literal> if <literal>zval *z_resource</literal> is given.</entry> </row> <row> <entry colname="col1"><literal>default_rsrc_id</literal></entry> <entry colname="col2">This integer specifies the default resource <literal>ID</literal> if no resource could be fetched or -1.</entry> </row> <row> <entry colname="col1"><literal>resource_type_name</literal></entry> <entry colname="col2">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.</entry> </row> <row> <entry colname="col1"><literal>resource_type</literal></entry> <entry colname="col2">The <literal>resource_type</literal> you got back when registering the resource destruction handler. In our example this was <envar>le_myresource</envar>.</entry> </row> </tbody> </tgroup> </informaltable> 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 <literal>NULL</literal> if there was a problem retrieving the resource. </para> <para> To force removal of a resource from the list, use the function <function>zend_list_delete</function>. 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 <function>zend_list_addref</function>. To search for previously allocated resource entries, use <function>zend_list_find</function>. The complete API can be found in <filename>zend_list.h</filename>. </para> </sect2> <sect2 id="zend.variables.global"> <title>Macros for Automatic Global Variable Creation</title> <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 <xref linkend='tab.macros-global-vars'/> describes macros that do exactly this task. They don't need any <envar>zval</envar> allocation; you simply have to supply a variable name and value. </para> <table id='tab.macros-global-vars'> <title>Macros for Global Variable Creation</title> <!-- <programlisting> Note: All macros in this table create a global variable of the name "name" with the value "value". </programlisting> --> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="*"/> <colspec colnum="2" colname="col2" colwidth="*"/> <tbody> <row> <entry colname="col1">Macro</entry> <entry colname="col2">Description</entry> </row> <row> <entry colname="col1"><literal>SET_VAR_STRING(name, value)</literal></entry> <entry colname="col2">Creates a new string.</entry> </row> <row> <entry colname="col1"><literal>SET_VAR_STRINGL(name, value, length)</literal></entry> <entry colname="col2">Creates a new string of the specified length. This macro is faster than <literal>SET_VAR_STRING</literal> and also binary-safe.</entry> </row> <row> <entry colname="col1"><literal>SET_VAR_LONG(name, value)</literal></entry> <entry colname="col2">Creates a new long.</entry> </row> <row> <entry colname="col1"><literal>SET_VAR_DOUBLE(name, value)</literal></entry> <entry colname="col2">Creates a new double.</entry> </row> </tbody> </tgroup> </table> </sect2> <sect2 id="zend.variables.constant"> <title>Creating Constants</title> <para> Zend supports the creation of true constants (as opposed to regular variables). Constants are accessed without the typical dollar sign (<literal>$</literal>) prefix and are available in all scopes. Examples include <literal>TRUE</literal> and <literal>FALSE</literal>, to name just two. </para> <para> To create your own constants, you can use the macros in <xref linkend='tab.create-const'/>. All the macros create a constant with the specified name and value. </para> <para> You can also specify flags for each constant: <itemizedlist> <listitem> <para> <literal>CONST_CS</literal> - This constant's name is to be treated as case sensitive. </para> </listitem> <listitem> <para> <literal>CONST_PERSISTENT</literal> - This constant is persistent and won't be "forgotten" when the current process carrying this constant shuts down. </para> </listitem> </itemizedlist> To use the flags, combine them using a inary OR: <programlisting> // register a new constant of type "long" REGISTER_LONG_CONSTANT("NEW_MEANINGFUL_CONSTANT", 324, CONST_CS | CONST_PERSISTENT); </programlisting> There are two types of macros - <literal>REGISTER_*_CONSTANT</literal> and<literal>REGISTER_MAIN_*_CONSTANT</literal>. 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. </para> <table id='tab.create-const'> <title>Macros for Creating Constants</title> <tgroup cols="2"> <colspec colnum="1" colname="col1" colwidth="1.53*"/> <colspec colnum="2" colname="col2" colwidth="1.00*"/> <tbody> <row> <entry colname="col1">Macro</entry> <entry colname="col2">Description</entry> </row> <row> <entry colname="col1"> <literal>REGISTER_LONG_CONSTANT(name, value, flags)</literal> <literal>REGISTER_MAIN_LONG_CONSTANT(name, value, flags)</literal> </entry> <entry colname="col2">Registers a new constant of type long.</entry> </row> <row> <entry colname="col1"> <literal>REGISTER_DOUBLE_CONSTANT(name, value, flags)</literal> <literal>REGISTER_MAIN_DOUBLE_CONSTANT(name, value, flags)</literal> </entry> <entry colname="col2">Registers a new constant of type double.</entry> </row> <row> <entry colname="col1"> <literal>REGISTER_STRING_CONSTANT(name, value, flags)</literal> <literal>REGISTER_MAIN_STRING_CONSTANT(name, value, flags)</literal> </entry> <entry colname="col2"> Registers a new constant of type string. The specified string must reside in Zend's internal memory.</entry> </row> <row> <entry colname="col1"> <literal>REGISTER_STRINGL_CONSTANT(name, value, length, flags)</literal> <literal>REGISTER_MAIN_STRINGL_CONSTANT(name, value, length, flags)</literal> </entry> <entry colname="col2">Registers a new constant of type string. The string length is explicitly set to <envar>length</envar>. The specified string must reside in Zend's internal memory.</entry> </row> </tbody> </tgroup> </table> </sect2> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/co.php/phpdoc/en/internals/zendapi/where-to-go.xml?r=1.1&p=1 Index: phpdoc/en/internals/zendapi/where-to-go.xml +++ phpdoc/en/internals/zendapi/where-to-go.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <!-- $Revision: 1.1 $ --> <sect1 id="zend.where-to-go"> <title>Where to Go from Here</title> <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. </para> <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 <filename>ext/standard</filename> 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. </para> </sect1> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 -->
« previous php.doc (#969369674) next »