05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

using SEPARATE_ZVAL( ), initializes the return_value to be an array, and fills in the<br />

array. The big trick here is the zval_add_ref( ) call. This function increments the reference<br />

count on the zval container. Therefore, instead of making n copies of the container,<br />

one for each element, we have only one copy, with a reference count of n+1.<br />

Remember, is_ref is still 0 here.<br />

Here’s how this function could be used in a <strong>PHP</strong> script:<br />

<br />

This would result in a two-dimensional array that looks like this:<br />

$arr[0][0] = 1 $arr[0][1] = 2 $arr[0][2] = 3<br />

$arr[1][0] = 1 $arr[1][1] = 2 $arr[1][2] = 3<br />

$arr[2][0] = 1 $arr[2][1] = 2 $arr[2][2] = 3<br />

Internally, a copy-on-write of the appropriate container is done if any of these array<br />

elements are changed. The engine knows to do a copy-on-write when it sees something<br />

being assigned to a zval container whose reference count is greater than 1 and<br />

whose is_ref is 0. We could have written our function to do a MAKE_STD_ZVAL( ) for<br />

each element in our array, but it would have been about twice as slow as simply<br />

incrementing the reference count and letting a copy-on-write make a separate copy<br />

later if necessary.<br />

Global Variables<br />

To access an internal <strong>PHP</strong> global variable from a function in your extension, you first<br />

have to determine what kind of global variable it is. There are three main types: SAPI<br />

globals, executor globals, and extension globals.<br />

SAPI Globals (SG)<br />

SAPI is the Server Abstraction API. It contains any variables related to the web server<br />

under which <strong>PHP</strong> is running. Note that not all SAPI modules are related to web servers.<br />

The command-line version of <strong>PHP</strong>, for example, uses the CGI SAPI layer. There<br />

is also a Java SAPI module. You can check which SAPI module you are running<br />

under by including SAPI.h and then checking sapi_module.name:<br />

#include <br />

/* then in a function */<br />

printf("the SAPI module is %s\n", sapi_module.name);<br />

See the sapi_globals_struct in the main/SAPI.h file for a list of available SAPI globals.<br />

For example, to access the default_mimetype SAPI global, you would use:<br />

SG(default_mimetype)<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

Global Variables | 343

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!