CKTIS / PHP
Variable scope and lifetime
Local variables ordinarily start afresh on each call.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
static $calls = 0;Local variables ordinarily start afresh on each call. A static local retains its value between calls during the execution and remains private to that function scope. An outer variable with the same spelling is separate unless the function explicitly binds it using global or a closure capture.
$calls=20; function ticket(){static $calls=0; return ++$calls;}
echo json_encode([ticket(),ticket(),$calls]);
[1,2,20]
Examples
<?php
$calls=20; function ticket(){static $calls=0; return ++$calls;}
echo json_encode([ticket(),ticket(),$calls]);
Result
[1,2,20]