如果我有使用 static
变量进行缓存的代码,如下所示:
class BossParty
{
// ...
public function getTemplate()
{
static $template;
if ($template == null)
{
$template = BossTemplate::get($this->templateID);
}
return $template;
}
// ...
}
$template
会在 BossParty
的不同实例中持续存在吗?我试过检查 php.net,但我只能找到有关静态类变量的信息。
最佳答案
是的,静态变量将在类的实例中持续存在。
例子:
<?php
class Test {
public function __construct() {
static $foo;
if ($foo) {
echo 'found';
} else {
$foo = 'foobar';
}
}
}
$test1 = new Test();
$test2 = new Test();
// output "found"
请注意,这对于后代类也是如此。如果我们有一个扩展 Test
的类 Child
,调用 parent::__construct
(无论是显式还是隐式)将使用相同的 值>$foo
.
关于php - PHP 函数中的静态变量是否跨实例全局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6015891/