phpstudy nginx 配置(php5.6+nginx),microMVC框架,配置到public目录后,访问到其下面的index.php后显示(如图)!

Access denied | coolestguidesontheplanet.com used Cloudflare to restrict access
Please enable cookies.
What happened?
The owner of this website (coolestguidesontheplanet.com) has banned your access based on your browser's signature (3e6cd6-ua98).Keyboard Shortcuts?
Next menu item
Previous menu item
Previous man page
Next man page
Scroll to bottom
Scroll to top
Goto homepage
Goto search(current page)
Focus search box
Change language:
Brazilian Portuguese
Chinese (Simplified)
Zend API: Hacking the Core of PHP
Introduction
Those who know don't talk.
Those who talk don't know.
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.
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.
This information is currently rather outdated,
parts of it only cover early stages of the ZendEngine 1.0 API
as it was used in early versions of PHP 4.
More recent information may be found in the various README files that
come with the PHP source and the
section on the Zend website.
&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.
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.
What Is Zend? and What Is PHP?
The name Zend refers to the language engine,
PHP's core. The term PHP 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 (
). To implement a Web script interpreter, you need
three parts:
The interpreter part analyzes the input
code, translates it, and executes it.
The functionality part implements the
functionality of the language (its functions, etc.).
The interface part talks to the Web
server, etc.
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.
The following sections discuss where PHP can be extended and how
it's done.
Extension Possibilities
As shown , PHP can be extended primarily at
three points: external modules, built-in modules, and the Zend
engine. The following sections discuss these options.
External Modules
External modules can be loaded at script runtime using the
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:
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.
Third parties might consider using the
extension tag in php.ini
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
Built-in Modules
Built-in modules are compiled directly into PHP and carried around
with every PHP 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:
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.
The Zend Engine
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.
Source Layout
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
and, of course, with PHP (available at
it need to be said?).
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.
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.
The following table describes the contents of the major directories.
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:
php-src/main/php.h, located in the main PHP directory.
This file contains most of PHP's macro and API definitions.
php-src/Zend/zend.h, located in the main Zend directory.
This file contains most of Zend's macros and definitions.
php-src/Zend/zend_API.h, also located in the Zend
directory, which defines Zend's API.
You should also follow some sub-inclusions from
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.
Extension Conventions
Zend is built using to avoid breaking its
standards, you should follow the rules described in the following
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
zend.h and zend_API.h.
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.)
Memory Management
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
emalloc(),
estrdup(),
estrndup(),
ecalloc(), and erealloc()
allo efree() frees these
previously allocated blocks. Memory handled by the
e*() functions is considered local to the
current process and is discarded as soon as the script executed by
this process is terminated.
To allocate resident memory that survives termination of
the current script, you can use malloc() and
free(). This should only be done with extreme
care, however, and only in conjunction with demands of the Zend
API; otherwise, you risk memory leaks.
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.
Directory and File Functions
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.
String Handling
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 e*() functions for allocation. (This might
not make m just keep it somewhere in your head for now - we'll get
back to it shortly.)
Complex Types
Complex types such as arrays and objects require
different treatment. Zend features a single API for these types - they're
stored using hash tables.
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.
PHP's Automatic Build System
PHP 4 features an automatic build system that's very flexible.
All modules reside in a subdirectory of the
ext directory. In addition to its own sources,
each module consists of a config.m4 file, for extension configuration. (for example, see
All these stub files are generated automatically, along with
.cvsignore, by a little shell script named
ext_skel that resides in the
ext 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.
Step by step, the process looks like
:~/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:
$ vi ext/my_module/config.m4
$ ./buildconf
$ ./configure --[with|enable]-my_module
$ ./php -f ext/my_module/my_module.php
$ vi ext/my_module/my_module.c
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.
This instruction creates the
aforementioned files. To include the new module in the automatic
configuration and build process, you have to run
buildconf, which regenerates the
configure script by searching through the
ext directory and including all found
config.m4 files.
The default config.m4 shown in
is a bit more complex:
Example #1 The default config.m4.
dnl $Id: build.xml 0-03-29 16:25:51Z degeberg $
dnl config.m4 for extension my_module
dnl Comments in this file start with the string 'dnl'.
dnl Remove where necessary. This file will not work
dnl without editing.
dnl If your extension references something external, use with:
dnl PHP_ARG_WITH(my_module, for my_module support,
dnl Make sure that the comment is aligned:
--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:
--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
MY_MODULE_DIR=$PHP_MY_MODULE
dnl else # search default path list
AC_MSG_CHECKING([for my_module files in default path])
for i in $SEARCH_PATH ; do
if test -r $i/$SEARCH_FOR; then
MY_MODULE_DIR=$i
AC_MSG_RESULT(found in $i)
dnl if test -z &$MY_MODULE_DIR&; then
AC_MSG_RESULT([not found])
AC_MSG_ERROR([Please reinstall the my_module distribution])
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,
PHP_ADD_LIBRARY_WITH_PATH($LIBNAME, $MY_MODULE_DIR/lib, MY_MODULE_SHARED_LIBADD)
AC_DEFINE(HAVE_MY_MODULELIB,1,[ ])
AC_MSG_ERROR([wrong my_module lib version or lib not found])
-L$MY_MODULE_DIR/lib -lm -ldl
dnl PHP_SUBST(MY_MODULE_SHARED_LIBADD)
PHP_NEW_EXTENSION(my_module, my_module.c, $ext_shared)
If you're unfamiliar with M4 files (now is certainly a good
time to get familiar), this might be a bi but
it's actually quite easy.
Note: Everything prefixed with
dnl is treated as a comment and is not
The config.m4 file is responsible for
parsing the command-line options passed to
configure at configuration time. This means
that it has to check for required external files and do similar
configuration and setup tasks.
The default file creates two configuration directives in the
configure script:
--with-my_module and
--enable-my_module. Use the first option when
referring external files (such as the
--with-apache 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,
that is, if you're using --enable-my_module, you
should remove support for --with-my_module, and
vice versa.
By default, the config.m4 file created by
ext_skel accepts both directives and
automatically enables your extension. Enabling the extension is
done by using the PHP_EXTENSION macro. To change
the default behavior to include your module into the PHP binary
when desired by the user (by explicitly specifying
--enable-my_module or
--with-my_module), change the test for
$PHP_MY_MODULE to == &yes&:
if test &$PHP_MY_MODULE& == &yes&; then dnl
Action.. PHP_EXTENSION(my_module, $ext_shared)
This would require you to use
--enable-my_module each time when reconfiguring
and recompiling PHP.
Note: Be sure to run
buildconf every time you change
config.m4!
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.
Creating Extensions
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.
shows the source.
Example #2 A simple extension.
/* 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)
ZEND_FE_END
/* compiled module information */
zend_module_entry firstmod_module_entry =
STANDARD_MODULE_HEADER,
&First Module&,
firstmod_functions,
NO_VERSION_YET,
STANDARD_MODULE_PROPERTIES
/* implement standard &stub& routine to introduce ourselves to Zend */
#if COMPILE_DL_FIRST_MODULE
ZEND_GET_MODULE(firstmod)
/* implement function that is meant to be made available to PHP */
ZEND_FUNCTION(first_module)
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, &l&, &parameter) == FAILURE) {
RETURN_LONG(parameter);
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.)
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.
Compiling Modules
There are basically two ways to compile modules:
Use the provided &make& mechanism in the
ext directory, which also allows building
of dynamic loadable modules.
Compile the sources manually.
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.
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.
Compiling Using Make
To compile the sample sources using the standard mechanism, copy
all their subdirectories to the ext
directory of your PHP source tree. Then run
buildconf, which will create an updated
configure 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
After you run buildconf, configure
--help shows the following additional modules:
--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
The module shown earlier in
can be enabled with
--enable-first_module or
--enable-first_module=yes.
Compiling Manually
To compile your modules manually, you need the following commands:
The command to compile the module simply instructs the compiler
to generate position-independent code (-fpic shouldn't be
omitted) and additionally defines the constant
COMPILE_DL_FIRST_MODULE to
tell the module code that it's compiled as a dynamically loadable module (the
test module a 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.
Note: All include paths in the example are
relative to the directory ext. If you're
compiling from another directory, change the pathnames
accordingly. Required items are the PHP directory, the
Zend directory, and (if necessary), the
directory in which your module resides.
The link command is also a plain vanilla command instructing linkage as a dynamic module.
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).
Note: 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.)
Using Extensions
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 first_module.c as a shared object, your result file
should be first_module.so. 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 htdocs directory and try it with
the source in .
If you compiled it into the PHP binary,
omit the call to , as the module's
functionality is instantly available to your scripts.
For security reasons, you should not put your
dynamic modules into publicly accessible directories. Even though it can be
done and it simplifies testing, you should put them into a separate directory
in production environments.
Example #3 A test file for first_module.so.
&?php&&&&//&remove&next&comment&if&necessary//&dl("first_module.so");&$param&=&2;$return&=&first_module($param);print("We&sent&'$param'&and&got&'$return'");?&
Calling this PHP file should output the following:
We sent '2' and got '2'
If required, the dynamic loadable module is loaded by calling the
function. This function looks for the
specified shared object, loads it, and makes its functions
available to PHP. The module exports the function
first_module(), which accepts a single
parameter, converts it to an integer, and returns the result of the
conversion.
If you've gotten this far, congratulations! You just built your
first extension to PHP.
Troubleshooting
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 ext directory with the fresh
this will guarantee a safe compilation environment. If this
fails, try manual compilation.
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
it doesn't occur with static modules. Errors in static
modules show up at compile time.
Source Discussion
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.
Module Structure
All PHP modules follow a common structure:
Header file inclusions (to include all required macros, API
definitions, etc.)
C declaration of exported functions (required to declare the Zend
function block)
Declaration of the Zend function block
Declaration of the Zend module block
Implementation of get_module()
Implementation of all exported functions
Declaring Exported Functions
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:
ZEND_FUNCTION ( my_function );
ZEND_FUNCTION declares a new C function that complies
with Zend's internal API. This means that the function is of
type void and
accepts INTERNAL_FUNCTION_PARAMETERS (another macro) as
parameters. Additionally, it prefixes the function name with
zif. The immediately expanded version of the above
definitions would look like this:
void zif_my_function ( INTERNAL_FUNCTION_PARAMETERS );
Expanding INTERNAL_FUNCTION_PARAMETERS
results in the following:
void zif_my_function( int ht
, zval * return_value
, zval * this_ptr
, int return_value_used
, zend_executor_globals * executor_globals
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 zval
and pval are identical. zval is
Zend' pval is PHP's definition
(actually, pval is an alias for zval
now). As the macro INTERNAL_FUNCTION_PARAMETERS
is a Zend macro, the above declaration contains
zval. When writing code, you should always use
zval to conform to the new Zend API.
The parameter list of this declarati you should keep these parameters in mind (see
for descriptions).
Zend's Parameters to Functions Called from PHP
Description
The number of arguments passed to the Zend function.
You should not touch this directly, but instead use ZEND_NUM_ARGS() to obtain the
return_value
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.
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 getThis() to obtain this pointer.
return_value_used
This flag indicates whether an eventual return value
from this function will actually be used by the calling script.
0 indicates that the retu
1 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 array.c makes use of
executor_globals
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 TSRMLS_FETCH().
Declaration of the Zend Function Block
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 zend_function_entry. 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, zend_function_entry is defined as shown in
Example #4 Internal declaration of zend_function_entry.
typedef struct _zend_function_entry {
void (*handler)(INTERNAL_FUNCTION_PARAMETERS);
unsigned char *func_arg_
} zend_function_
In the example above, the declaration looks like this:
zend_function_entry firstmod_functions[] =
ZEND_FE(first_module, NULL)
ZEND_FE_END
You can see that the last entry in the list always has to be
ZEND_FE_END.
This marker has to be set for Zend to know when the end of the
list of exported functions is reached.
The macro ZEND_FE (short for 'Zend Function
Entry') simply expands to a structure entry in
zend_function_entry. Note that these macros
introduce a special naming scheme to your functions - your C
functions will be prefixed with zif_, meaning
that ZEND_FE(first_module) will refer to a C
function zif_first_module(). If you want to mix
macro usage with hand-coded entries (not a good practice), keep
this in mind.
Tip: Compilation errors that refer to functions
named zif_*() relate to functions defined
with ZEND_FE.
shows a list of all the macros
that you can use to define functions.
Macros for Defining Functions
Macro Name
Description
ZEND_FE(name, arg_types)
Defines a function entry of the name name in
zend_function_entry. Requires a corresponding C
function. arg_types needs to be set to NULL.
This function uses automatic C function name generation by prefixing the PHP
function name with zif_.
For example, ZEND_FE(&first_module&, NULL) introduces a
function first_module() to PHP and links it to the C
function zif_first_module(). Use in conjunction
with ZEND_FUNCTION.
ZEND_NAMED_FE(php_name, name, arg_types)
Defines a function that will be available to PHP by the
name php_name and links it to the corresponding C
function name. arg_types needs to be set
to NULL. Use this function if you don't want the automatic
name prefixing introduced by ZEND_FE. Use in conjunction
with ZEND_NAMED_FUNCTION.
ZEND_FALIAS(name, alias, arg_types)
Defines an alias named alias for
name. arg_types needs to be set
to NULL. Doesn't require a corresponding C
refers to the alias target instead.
PHP_FE(name, arg_types)
Old PHP API equivalent of ZEND_FE.
PHP_NAMED_FE(runtime_name, name, arg_types)
Old PHP API equivalent of ZEND_NAMED_FE.
Note: You can't use
ZEND_FE in conjunction with
PHP_FUNCTION, or PHP_FE in
conjunction with ZEND_FUNCTION. However, it's
perfectly legal to mix ZEND_FE and
ZEND_FUNCTION with PHP_FE
and PHP_FUNCTION when staying with the same
macro set for each function to be declared. But mixing is
not instead, you're advised to
use the ZEND_* macros only.
Declaration of the Zend Module Block
This block is stored in the structure
zend_module_entry and contains all necessary
information to describe the contents of this module to Zend. You can
see the internal definition of this module in
Example #5 Internal declaration of zend_module_entry.
typedef struct _zend_module_entry zend_module_
struct _zend_module_entry {
unsigned int zend_
unsigned char zend_
zend_function_entry *
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);
[ Rest of the structure is not interesting here ]
In our example, this structure is implemented as follows:
zend_module_entry firstmod_module_entry =
STANDARD_MODULE_HEADER,
&First Module&,
firstmod_functions,
NULL, NULL, NULL, NULL, NULL,
NO_VERSION_YET,
STANDARD_MODULE_PROPERTIES,
This is basically the easiest and most minimal set of values you
could ever use. The module name is set to First
Module, then the function list is referenced, after which
all startup and shutdown functions are marked as being unused.
For reference purposes, you can find a list of the macros involved
in declared startup and shutdown functions in
. 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
(INIT_FUNC_ARGS and
SHUTDOWN_FUNC_ARGS), 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.
Macros to Declare Startup and Shutdown Functions
Description
ZEND_MINIT(module)
Declares a function for module startup. The generated name will
be zend_minit_&module& (for example,
zend_minit_first_module).
conjunction with ZEND_MINIT_FUNCTION.
ZEND_MSHUTDOWN(module)
Declares a function for module shutdown. The generated name
will be zend_mshutdown_&module& (for
example, zend_mshutdown_first_module).
in conjunction with ZEND_MSHUTDOWN_FUNCTION.
ZEND_RINIT(module)
Declares a function for request startup. The generated name
will be zend_rinit_&module& (for
example, zend_rinit_first_module).
conjunction with ZEND_RINIT_FUNCTION.
ZEND_RSHUTDOWN(module)
Declares a function for request shutdown. The generated name
will be zend_rshutdown_&module& (for
example, zend_rshutdown_first_module).
in conjunction with ZEND_RSHUTDOWN_FUNCTION.
ZEND_MINFO(module)
Declares a function for printing module information, used when
is called. The generated name will
be zend_info_&module& (for example,
zend_info_first_module).
Use in conjunction
with ZEND_MINFO_FUNCTION.
Creation of get_module()
This function is special to all dynamic loadable modules. Take a
look at the creation via the ZEND_GET_MODULE
macro first:
#if COMPILE_DL_FIRSTMOD
ZEND_GET_MODULE(firstmod)
The function implementation is surrounded by a conditional
compilation statement. This is needed since the function
get_module() is only required if your module is
built as a dynamic extension. By specifying a definition of
COMPILE_DL_FIRSTMOD 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 get_module() is simply left
get_module() is called by Zend at load time
of the module. You can think of it as being invoked by the
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.
If you don't implement a get_module() function in
your dynamic loadable module, Zend will compliment you with an error message
when trying to access it.
Implementation of All Exported Functions
Implementing the exported functions is the final step. The
example function in first_module looks like this:
ZEND_FUNCTION(first_module)
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, &l&, &parameter) == FAILURE) {
RETURN_LONG(parameter);
The function declaration is done
using ZEND_FUNCTION, which corresponds
to ZEND_FE in the function entry table (discussed
After the declaration, code for checking and retrieving the function's
arguments, argument conversion, and return value generation follows (more on
this later).
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.
Now, in the following sections, read on about how to make use of PHP's
internals to build powerful extensions.
Accepting Arguments
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.
PHP doesn't make use of any formal f 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.
Determining the Number of Arguments
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
ZEND_NUM_ARGS 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, ht, which is passed in the
INTERNAL_FUNCTION_PARAMETERS list. As
ht itself now contains the number of arguments that
have been passed to the function, ZEND_NUM_ARGS
has been stripped down to a dummy macro (see its definition in
zend_API.h). But it's still good practice to
use it, to remain compatible with future changes in the call
interface. Note: The old PHP equivalent of
this macro is ARG_COUNT.
The following code checks for the correct number of arguments:
if(ZEND_NUM_ARGS() != 2) WRONG_PARAM_COUNT;
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 WRONG_PARAM_COUNT,
which can be used to generate a standard error message like:
&Warning: Wrong parameter count for firstmodule() in /home/www/htdocs/firstmod.php on line 5&
This macro prints a default error message and then returns to the caller.
Its definition can also be found in zend_API.h and looks
like this:
ZEND_API void wrong_param_count(void);
#define WRONG_PARAM_COUNT { wrong_param_count(); }
As you can see, it calls an internal function
named wrong_param_count() that's responsible for printing
the warning. For details on generating customized error
messages, see the later section &Printing Information.&
Retrieving Arguments
New parameter parsing API
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.
Parsing parameters is a very common operation and it may get a bit
tedious. It would also be nice to have standardized error checking
and error messages. Since PHP 4.1.0, there is a way to do just
that by using the new parameter parsing API. It greatly simplifies
the process of receiving parameters, but it has a drawback in
that it can't be used for functions that expect variable number of
parameters. But since the vast majority of functions do not fall
into those categories, this parsing API is recommended as the new
standard way.
The prototype for parameter parsing function looks like this:
int zend_parse_parameters(int num_args TSRMLS_DC, char *type_spec, ...);
The first argument to this function is supposed to be the number
of actual parameters passed to your function, so
ZEND_NUM_ARGS() can be used for that. The
second parameter should always be TSRMLS_CC
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.
zend_parse_parameters() 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.
If the parameters could be obtained successfully and there were no
errors during type conversion, the function will return
SUCCESS, otherwise it will return
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.
Here are some sample error messages:
Warning - ini_get_all() requires at most 1 parameter, 2 given
Warning - wddx_deserialize() expects parameter 1 to be string, array given
Of course each error message is accompanied by the filename and
line number on which it occurs.
Here is the full list of type specifiers:
d - double
s - string (with possible null bytes) and its length
b - boolean
r - resource, stored in zval*
a - array, stored in zval*
o - object (of any class), stored in zval*
O - object (of class specified by class entry), stored in zval*
z - the actual zval*
The following characters also have a meaning in the specifier
| - 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
/ - the parsing function will
call SEPARATE_ZVAL_IF_NOT_REF() on
the parameter it follows, to provide a copy of the
parameter, unless it's a reference.
! - the parameter it follows can
be of specified type or NULL (only
applies to a, o, O, r, and z). If NULL
value is passed by the user, the storage pointer will be
set to NULL.
The best way to illustrate the usage of this function is through
/* Gets a long, a string and its length, and a zval. */
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,
&lsz&, &l, &s, &s_len, &param) == FAILURE) {
/* Gets an object of class specified by my_ce, and an optional double. */
double d = 0.5;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,
&O|d&, &obj, my_ce, &d) == FAILURE) {
/* Gets an object or null, and an array.
If null is passed for object, obj will be set to NULL. */
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, &O!a&, &obj, &arr) == FAILURE) {
/* Gets a separated array. */
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, &a/&, &arr) == FAILURE) {
/* Get only the first three parameters (useful for varargs functions). */
if (zend_parse_parameters(3, &zbr!&, &z, &b, &r) == FAILURE) {
Note that in the last example we pass 3 for the number of received
parameters, instead of ZEND_NUM_ARGS(). 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
zend_get_parameters_array_ex() to obtain
The parsing function has an extended version that allows for an
additional flags argument that controls its actions.
int zend_parse_parameters_ex(int flags, int num_args TSRMLS_DC, char *type_spec, ...);
The only flag you can pass currently is ZEND_PARSE_PARAMS_QUIET,
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.
For example, here is how you would get either a set of three longs
or a string:
long l1, l2, l3;
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 */
php_error(E_WARNING, &%s() takes either three long values or a string as argument&,
get_active_function_name(TSRMLS_C));
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.
Old way of retrieving arguments (deprecated)
Deprecated parameter parsing API
This API is deprecated and superseded by the new ZEND
parameter parsing API.
After having checked the number of arguments, you need to get access
to the arguments themselves. This is done with the help of
zend_get_parameters_ex():
if(zend_get_parameters_ex(1, &parameter) != SUCCESS)
WRONG_PARAM_COUNT;
All arguments are stored in a zval container,
which needs to be pointed to twice. The snippet above
tries to retrieve one argument and make it available to us via the
parameter pointer.
zend_get_parameters_ex() 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 func 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
zvals. (Confusing, isn't it?) All these pointers
are required because Zend works internally with
**zval; to adjust a local **zval in
our function,zend_get_parameters_ex() requires
a pointer to it.
The return value of zend_get_parameters_ex()
can either be SUCCESS or
FAILURE, 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
WRONG_PARAM_COUNT.
To retrieve more than one argument, you can use a similar snippet:
zval **param1, **param2, **param3, **param4;
if(zend_get_parameters_ex(4, &param1, &param2, &param3, &param4) != SUCCESS)
WRONG_PARAM_COUNT;
zend_get_parameters_ex() 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 zend_get_parameters_ex(), you won't
get an error but will get the first three parameters instead.
Subsequent calls of zend_get_parameters_ex()
won't retrieve the remaining arguments, but will get the same
arguments again.
Dealing with a Variable Number of Arguments/Optional Parameters
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
zend_get_parameters_ex() for every possible
number of arguments, which is often unsatisfying.
For this case, you can use the
function zend_get_parameters_array_ex(), which accepts the
number of parameters to retrieve and an array in which to store them:
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;
First, the number of arguments is checked to make sure that it's in the accepted range. After that,
zend_get_parameters_array_ex() is used to
fill parameter_array with valid pointers to the argument
A very clever implementation of this can be found in the code
handling PHP's
located in
ext/standard/fsock.c, as shown in
. Don't worry if you don't know all the functions used in this
we'll get to them shortly.
Example #6 PHP's implementation of variable arguments in fsockopen().
pval **args[5];
int *sock=emalloc(sizeof(int));
int arg_count=ARG_COUNT(ht);
int socketd = -1;
unsigned char udp = 0;
struct timeval timeout = { 60, 0 };
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) {
convert_to_double_ex(args[4]);
conv = (unsigned long) (Z_DVAL_PP(args[4]) * );
timeout.tv_sec = conv / 1000000;
timeout.tv_usec = conv % 1000000;
/* fall-through */
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 */
if (!PZVAL_IS_REF(*args[2])) {
php_error(E_WARNING,&error argument to fsockopen not passed by reference&);
ZVAL_LONG(*args[2], 0);
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);
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 switch() statement
to deal with all arguments. The
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 break keyword in all stages. After
having processed the last case, it exits the
switch() statement and does the minimal
argument processing needed if the function is invoked with only
two arguments.
This multiple-stage type of processing, similar to a stairway, allows
convenient processing of a variable number of arguments.
Accessing Arguments
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.
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
Note: All conversion functions expect a
**zval as parameter.
Argument Conversion Functions
Description
convert_to_boolean_ex()
Forces conversion to a Boolean type. Boolean values remain
untouched. Longs, doubles, and strings containing
0 as well as NULL values will result in
Boolean 0 (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 1 (TRUE).
convert_to_long_ex()
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 0.
Arrays and objects are converted to 0 if
1 otherwise.
convert_to_double_ex()
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 0.0. Arrays and
objects are converted to 0.0 if empty,
1.0 otherwise.
convert_to_string_ex()
Forces conversion to a string. Strings remain untouched. NULL
values are converted to an empty string. Booleans containing
TRUE are converted to &1&, otherwise
resulting in an empty string. Longs and doubles are converted
to their corresponding string representation. Arrays are
converted to the string &Array& and
objects to the string &Object&.
convert_to_array_ex(value)
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 0.
convert_to_object_ex(value)
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 scalar , having the
corresponding source value as content.
convert_to_null_ex(value)
Forces the type to become a NULL value, meaning empty.
You can find a demonstration of the behavior in
cross_conversion.php on the accompanying
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,
0 for numeric values, FALSE
for Booleans) to ensure a defined state.
Following is a quote from the sample module discussed
previously, which makes use of the conversion functions:
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));
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 zval type, whose definition is shown in .
Example #7 PHP/Zend zval type definition.
typedef struct _zval_
typedef union _zvalue_value {
/* long value */
/* double value */
HashTable *
/* hash table value */
zend_class_entry *
HashTable *
struct _zval_struct {
/* Variable information */
/* value */
/* active type */
unsigned char is_
Actually, pval (defined in php.h) is
only an alias of zval (defined in zend.h),
which in turn refers to _zval_struct. This is a most interesting
structure. _zval_struct is the &master& structure, containing
the value structure, type, and reference information. The substructure
zvalue_value 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
Zend zval Structure
Description
Union containing this variable's contents. See
for a description.
Contains this variable's type. For a list of available
types, see .
0 means that this variabl 1 means that this variable is a reference to another variable.
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.
Zend zvalue_value Structure
Description
Use this property if the variable is of the
type IS_LONG,
IS_BOOLEAN, or IS_RESOURCE.
Use this property if the variable is of the
type IS_DOUBLE.
This structure can be used to access variables of
the type IS_STRING. The member len contains the
the member val points to the string itself. Zend
uses C thus, the string length contains a trailing
This entry points to the variable's hash table entry if the variable is an array.
Use this property if the variable is of the
type IS_OBJECT.
Zend Variable Type Constants
Description
Denotes a NULL (empty) value.
A long (integer) value.
A double (floating point) value.
Denotes an array.
An object.
A Boolean value.
IS_RESOURCE
A resource (for a discussion of resources, see the
appropriate section below).
IS_CONSTANT
A constant (defined) value.
To access a long you access zval.value.lval, to
access a double you use zval.value.dval, and so on.
Because all values are stored in a union, trying to access data
with incorrect union members results in meaningless output.
Accessing arrays and objects is a bit more complicated and
is discussed later.
Dealing with Arguments Passed by Reference
If your function accepts arguments passed by reference that you
intend to modify, you need to take some precautions.
What we didn't say yet is that under the circumstances presented so
far, you don't have write access to any zval containers
designating function parameters that have been passed to you. Of course, you
can change any zval containers that you created within
your function, but you mustn't change any zvals that refer to
Zend-internal data!
We've only discussed the so-called *_ex() API
so far. You may have noticed that the API functions we've used are
called zend_get_parameters_ex() instead of
zend_get_parameters(),
convert_to_long_ex() instead of
convert_to_long(), etc. The
*_ex() 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
Because Zend works internally with references, different variables
may reference the same value. Write access to a
zval container requires this container to contain
an isolated value, meaning a value that's not referenced by any
other containers. If a zval container were
referenced by other containers and you changed the referenced
zval, you would automatically change the contents
of the other containers referencing this zval
(because they'd simply point to the changed value and thus change
their own value as well).
zend_get_parameters_ex() doesn't care about
this situation, but simply returns a pointer to the desired
zval containers, whether they consist of references
or not. Its corresponding function in the traditional API,
zend_get_parameters(), immediately checks for
referenced values. If it finds a reference, it creates a new,
isolated zval copies the referenced data
into this n and then returns a pointer to the
new, isolated value.
This action is called zval separation
(or pval separation). Because the *_ex() API
doesn't perform zval separation, it's considerably faster, while
at the same time disabling write access.
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 $parameter is being passed as an isolated value, rendering it
to a write-safe state:
my_function(&$parameter);
But this is not the case with regular parameters!
All other parameters that are not passed by reference are in a read-only
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
PZVAL_IS_REF. This macro accepts a zval*
to check if it is a reference or not. Examples are given in
Example #8 Testing for referenced parameter passing.
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, &z&, &parameter) == FAILURE)
/* 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);
Assuring Write Safety for Other Parameters
You might run into a situation in which you need write access to a
parameter that's retrieved with zend_get_parameters_ex()
but not passed by reference. For this case, you can use the macro
SEPARATE_ZVAL, which does a zval separation on the provided
container. The newly generated zval 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:
/* 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 */
SEPARATE_ZVAL uses emalloc()
to allocate the new zval 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.
Note: As you can easily work around the lack
of write access in the &traditional& API (with
zend_get_parameters() and so on), this API
seems to be obsolete, and is not discussed further in this
Creating Variables
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
To create new variables that can be seen &from the outside& by the
executing script, you need to allocate a new zval
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:
zval *new_
/* 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 */
The macro MAKE_STD_ZVAL allocates a new
zval container using ALLOC_ZVAL
and initializes it using INIT_ZVAL. As
implemented in Zend at the time of this writing,
initializing means setting the reference
count to 1 and clearing the
is_ref flag, but this process could be extended
later - this is why it's a good idea to keep using
MAKE_STD_ZVAL instead of only using
ALLOC_ZVAL. If you want to optimize for speed
(and you don't have to explicitly initialize the
zval container here), you can use
ALLOC_ZVAL, but this isn't recommended because
it doesn't ensure data integrity.
ZEND_SET_SYMBOL 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 zval container). This is the preferred method
if speed is not a crucial issue and you'd like to keep memory
usage low.
Note that ZEND_SET_SYMBOL makes use of the Zend
executor globals via the macro EG. By
specifying EG(active_symbol_table), 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.
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
zend_hash_update():
zval *new_
/* allocate and initialize new container */
MAKE_STD_ZVAL(new_variable);
/* set type and variable contents here, see the following sections */
/* introduce this variable by the name &new_variable_name& into the symbol table */
zend_hash_update(
EG(active_symbol_table),
&new_variable_name&,
strlen(&new_variable_name&) + 1,
&new_variable,
sizeof(zval *),
This is actually the standard method used in most modules.
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:
zval *new_
// allocate and initialize new container
MAKE_STD_ZVAL(new_variable);
// set type and variable contents here
// introduce this variable by the name &new_variable_name& into the global symbol table
ZEND_SET_SYMBOL(&EG(symbol_table), &new_variable_name&, new_variable);
The macro ZEND_SET_SYMBOL is now being
called with a reference to the main, global symbol table by referring
EG(symbol_table).
Note: The active_symbol_table
variable is a pointer, but symbol_table is not.
This is why you have to use
EG(active_symbol_table) and
&EG(symbol_table) as parameters to
ZEND_SET_SYMBOL - it requires a pointer.
Similarly, to get a more efficient version, you can hardcode the
symbol table update:
zval *new_
// allocate and initialize new container
MAKE_STD_ZVAL(new_variable);
// set type and variable contents here
// introduce this variable by the name &new_variable_name& into the global symbol table
zend_hash_update(
&EG(symbol_table),
&new_variable_name&,
strlen(&new_variable_name&) + 1,
&new_variable,
sizeof(zval *),
shows a sample source that
creates two variables - local_variable with a local scope
and global_variable with a global scope (see Figure 9.7).
The full example can be found on the CD-ROM.
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 global $global_ in the PHP source.
Longs (Integers)
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 zval.value container structure discussed earlier in this
chapter, you can see that the long data type is directly contained in the union,
namely in the lval field. The corresponding
type value for}

我要回帖

更多关于 nginx php fpm 配置 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信