takeshin
takeshin

Reputation: 50658

How to use zval in PHP?

Could you suggest me any practical example showing how to make use zval containers? The only related function I know is debug_zval_dump, but I never really used it.

Edit:

I suppose, tracking zval containers I could see how to optimize the code, see how the memory is used by references. It seems it could be useful tool in some cases. There is certainly some good reason that debug_val_dump function exists for.

Upvotes: 4

Views: 2783

Answers (3)

Alireza Rahmani Khalili
Alireza Rahmani Khalili

Reputation: 2954

I could see how to optimize the code

PHP has optimizations for assigning by value. PHP accomplishes this by only copying the value to a new zval when it changes, and initially pointing the new symbol to the same zval container. This mechanism is called “copy on write”. Here is an example to illustrate:

$a = "new string";
$b =& $a;
// the variable b points to the variable a
xdebug_debug_zval( 'a' );
xdebug_debug_zval( 'b' );
// change the string and see that the refcount is reset
$b = 'changed string';
xdebug_debug_zval( 'a' );
xdebug_debug_zval( 'b' );

The output of this script is as follows:

a: (refcount=2, is_ref=0)='new string'
b: (refcount=2, is_ref=0)='new string'
a: (refcount=1, is_ref=0)='new string'
b: (refcount=1, is_ref=0)='changed string'

read more: php 7 zend certification study guide book

Upvotes: 0

Artefacto
Artefacto

Reputation: 97835

Every PHP variable is stored in a zval so you see your question doesn't really make sense.

debug_val_dump is not a very well thought out function because it's difficult to interpret. By simply passing a variable to the function you're changing the reference count of the zval. If you pass a reference to debug_val_dump without passing it by reference, you'll be forcing a zval separation and you'll always get back a zval with reference count 1 with reference flag clear, and if you pass it by reference (which must be done on call time, which is deprecated) then you can't tell, just by the output, if it was originally a reference or not.

Xdebug has a much more useful function where you don't pass the variable, you pass its name in a string instead. It's called xdebug_debug_zval.

Unless you're debugging code that uses references and you want to know how many variables belong to the reference set, these functions are probably not very useful for you.

To make any sense of them, I advise you to read reference count basics in the manual.

Upvotes: 11

Dennis Haarbrink
Dennis Haarbrink

Reputation: 3760

You can't really use zval's from php itself. It is a core implementation detail which is not (normally) accessible from userland php code.

Upvotes: 4

Related Questions