05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Along with this union, each container has a flag that holds the currently active type,<br />

whether it is a reference or not, and the reference count. So the actual pval/zval<br />

struct looks like this:<br />

struct _zval_struct {<br />

zvalue_value value;<br />

zend_uchar type;<br />

zend_uchar is_ref;<br />

zend_ushort refcount;<br />

};<br />

Because this structure could change in future versions of <strong>PHP</strong>, be sure to use the various<br />

access functions and macros described in the following sections, rather than<br />

directly manipulating the container.<br />

MAKE_STD_ZVAL( )<br />

The most basic of the pval/zval access macros provided by the extension API is the<br />

MAKE_STD_ZVAL( ) macro:<br />

zval *var;<br />

MAKE_STD_ZVAL(var);<br />

This does the following:<br />

• Allocates memory for the structure using emalloc( )<br />

• Sets the container reference count to 1<br />

• Sets the container is_ref flag to 0<br />

At this point, the container has no value—effectively, its value is null. In the “Accessor<br />

Macros” section, we’ll see how to set a container’s value.<br />

SEPARATE_ZVAL( )<br />

Another important macro is SEPARATE_ZVAL( ), used when implementing copy-onwrite<br />

kinds of behavior. This macro creates a separate copy of a zval container only<br />

if the structure to be changed has a reference count greater than 1. A reference count<br />

of 1 means that nothing else has a pointer to this zval, so we can change it directly<br />

and don’t need to copy off a new zval to change.<br />

Assuming a copy needs to be made, SEPARATE_ZVAL( ) decrements the reference count<br />

on the existing zval, allocates a new one, and does a deep copy of whatever value is<br />

stored in the original zval to the fresh copy. It then sets the reference count to 1 and<br />

is_ref to 0, just like MAKE_STD_ZVAL( ).<br />

zval_copy_ctor( )<br />

If you just want to make a deep copy directly and manage your own reference<br />

counts, you can call the zval_copy_ctor( ) function directly.<br />

332 | Chapter 14: Extending <strong>PHP</strong><br />

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

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

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

Saved successfully!

Ooh no, something went wrong!