In this tutorial you will learn how to manage integer cache values in PHP APC. I will explain the PHP functions apc_dec, apc_inc and apc_cas.
Code used during this tutorial:
1 2 3 4 5 6 7 8 9 10 11 12 |
# PHP APC Manage integer cache values # PHP scripts used apc_dec.php apc_inc.php apc_cas.php Useful links: http://php.net/manual/en/function.apc-dec.php http://php.net/manual/en/function.apc-inc.php http://php.net/manual/en/function.apc-cas.php https://en.wikipedia.org/wiki/Compare-and-swap |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php /** * apc_dec * Decrease a stored number * http://php.net/manual/en/function.apc-dec.php */ var_dump("Let's do something with success"); apc_store('anumber', 42); var_dump(apc_fetch('anumber')); var_dump(apc_dec('anumber')); var_dump(apc_dec('anumber', 10)); var_dump(apc_dec('anumber', 10, $success)); var_dump($success); var_dump("Now, let's fail"); apc_store('astring', 'foo'); $ret = apc_dec('astring', 1, $fail); var_dump($ret); var_dump($fail); ?> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php /** * apc_inc * Increase a stored number * http://php.net/manual/en/function.apc-inc.php */ var_dump("Let's do something with success"); apc_store('anumber', 42); var_dump(apc_fetch('anumber')); var_dump(apc_inc('anumber')); var_dump(apc_inc('anumber', 10)); var_dump(apc_inc('anumber', 10, $success)); var_dump($success); var_dump("Now, let's fail"); apc_store('astring', 'foo'); $ret = apc_inc('astring', 1, $fail); var_dump($ret); var_dump($fail); ?> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php /** * apc_cas * Updates an old value with a new value * http://php.net/manual/en/function.apc-cas.php * https://en.wikipedia.org/wiki/Compare-and-swap */ apc_store('foobar', 2); echo '$foobar = 2' . '<br />'; echo '$foobar == 1 ? 2 : 1 = ', (apc_cas('foobar', 1, 2) ? 'ok' : 'fail') . '<br />'; echo '$foobar == 2 ? 1 : 2 = ', (apc_cas('foobar', 2, 1) ? 'ok' : 'fail') . '<br />'; echo '$foobar = ', apc_fetch('foobar') . '<br />'; echo '$f__bar == 1 ? 2 : 1 = ', (apc_cas('f__bar', 1, 2) ? 'ok' : 'fail') . '<br />'; apc_store('perfection', 'xyz'); echo '$perfection == 2 ? 1 : 2 = ', (apc_cas('perfection', 2, 1) ? 'ok' : 'epic fail') . '<br />'; echo '$foobar = ', apc_fetch('foobar') . '<br />'; ?> |
Useful links:
http://php.net/manual/en/function.apc-dec.php
http://php.net/manual/en/function.apc-inc.php
http://php.net/manual/en/function.apc-cas.php
https://en.wikipedia.org/wiki/Compare-and-swap