全局静态变量是在函数内部定义的静态变量,它具有静态变量的特性,即在函数调用结束后不会被销毁,而是保留其值,直到程序结束。全局静态变量可以通过static
关键字来定义。
<?php
function counter() {
static $count = 0;
$count++;
echo "The counter is: $count\n";
}
counter(); // 输出: The counter is: 1
counter(); // 输出: The counter is: 2
counter(); // 输出: The counter is: 3
?>
问题1:静态变量在多线程环境下可能会出现问题
<?php
function threadSafeCounter() {
static $count = 0;
static $lock;
if (empty($lock)) {
$lock = new SplMutex();
}
$lock->lock();
$count++;
echo "The counter is: $count\n";
$lock->unlock();
}
// 模拟多线程环境
$threads = [];
for ($i = 0; $i < 10; $i++) {
$threads[$i] = new Thread(function() {
for ($j = 0; $j < 100; $j++) {
threadSafeCounter();
}
});
}
foreach ($threads as $thread) {
$thread->start();
}
foreach ($threads as $thread) {
$thread->join();
}
?>
问题2:静态变量的生命周期较长,可能会导致内存泄漏
<?php
function memoryLeakExample() {
static $data = [];
for ($i = 0; $i < 100000; $i++) {
$data[] = new stdClass();
}
// 手动释放引用
$data = null;
}
memoryLeakExample();
?>
没有搜到相关的文章